Alex Rivera | Logout

Mongoose/Mongo find in array of objectIds

Asked 2012-09-16T22:44:16.117
14

I have this item in mongo:

[ 
  { 
    title: 'Product Name',
    _id: 5052843e023273693300013c,
    description: 'This is a fake description',
    categories: [ 5052843e023273693300010a ],
  }
]

I want to find products like this that have this category. I have tried:

Product.find({ categories:  mongoose.Types.ObjectId('5052843e023273693300010a')})
Product.find({ categories:  mongoose.mongo.BSONPure.ObjectID.fromString('5052843e023273693300010a')})
Product.find({ categories:  '5052843e023273693300010a'})
Product.find({ 'categories':  '5052843e023273693300010a'})
Product.find({ categories:  {$in: ['5052843e023273693300010a']}})
Product.find({ categories:  Schema.Types.ObjectId('5052843e023273693300010a')})

But nothing works. I can fetch by id just fine using: _id: '5052843e023273693300013c'.

Note that when the products were inserted the category ID was added as a string (meaning I just assigned the ID instead of the category objects but that doesn't explain why none of the above work - it's unquoted in the dump so perhaps Mongo recognizes as an object ID.

Similar questions on SO did not yield an answer.

I am using the latest Mongoose (3 something) and recent Mongo, Node.

Update:

I can fetch just fine from CLI using:

db.products.find({ categories: '5052843e02327369330000fe' }); 

and interestingly I can fetch it by doing the not equal in my code - huh?:

Product.find({ categories: { $ne: '5052843e02327369330000fe' }})

My schema is as follows:

var Product = new Schema({
    title: { type: String, required: true },
    slug: { type: String },
    summary: { type: String }, //browser title
    description: { type: String, required: false },
    excerpt: { type: String },    //for a list and also for the meta description
    publish: { type: Boolean },
    featured: { type: Boolean },
    unavail
Edit
Report

1 Answer

0

What's happening is that Mongoose is casting whatever value you're using for a categories value in your Product.find call to an ObjectId as that's how categories is defined in the schema. But the document's categories value you're trying to match has a string type instead of an ObjectId so it's not matching.

To get things to work again you'll need to clean up your existing documents to match your defined schema.

answered 2012-09-16T23:26:45.157

Your Answer