3

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.

Community
  • 1
  • 1
Anoop
  • 5,540
  • 7
  • 35
  • 52

1 Answers1

12

Assuming arr is an array of strings representing ObjectId:

A.find({b : {
  $in: arr.map(function(o){ return mongoose.Types.ObjectId(o); })
}}, callback);
Yuri Zarubin
  • 11,439
  • 4
  • 30
  • 33
  • This still does not fetch any results. It returns an empty array – Anoop Feb 19 '15 at 05:33
  • This looks like correct syntax. Are you sure an `A` with the right `B` `_id`'s in its array exists in the collection? What happens if you try a similar query in the mongo shell? – wdberkeley Feb 19 '15 at 15:45
  • Ah..sorry. . this works. Turns out infact I was using the wrong id. Pardon my ignorance. Actually we need not even convert to ObjectId for it to work. – Anoop Feb 19 '15 at 21:23