Reputation: 5720
I am struggling with this since few hours now and hence posting here. I am trying to use find() operator in mongoose, to find whether a key matches any single element in the array, similar to How do I perform an id array query in Mongoose? but not getting expected results.
Here is my schema,
var a = new mongoose.Schema({
b : { type : mongoose.Schema.ObjectId, ref: 'B' },
});
var A = mongoose.model('A', a);
now I have an array , arr[], which holds some possible object id's of class B. i.e
arr = ["54e545fb6a0d90bb0772808b", "xxxxxxxxxxxxx", ...]
I want to find all documents of type A, where the field b matches any of the elements in arr. Note that arr is an array of strings, but b holds ObjectId.
So far I have tried,
A.find({b : {$in: arr}}, callback); //and
A.find({b : {$in: new ObjectId("54e545fb6a0d90bb0772808b")}}, callback); //manually got this one value from db
var callback = function (err, data) {
console.log("----------------------");
if (err)
console.log(err);
else {
console.log(JSON.stringify(data, null, '\t'));
}
console.log("----------------------");
}
Both of these does not seem to work. Thank you for the help.
Upvotes: 3
Views: 11766
Reputation: 11677
Assuming arr is an array of strings representing ObjectId:
A.find({b : {
$in: arr.map(function(o){ return mongoose.Types.ObjectId(o); })
}}, callback);
Upvotes: 12