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.

1 Answer 1

12

Assuming arr is an array of strings representing ObjectId:

A.find({b : {
  $in: arr.map(function(o){ return mongoose.Types.ObjectId(o); })
}}, callback);
Sign up to request clarification or add additional context in comments.

3 Comments

This still does not fetch any results. It returns an empty array
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?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.