choosyg
choosyg

Reputation: 794

Mongoose find all items with _id from an array that do exist

i know that i can search in mongoose like

schema.find( { '_id' : { $in: [1,2,3]} }, function(err,data){});

my problem is that e.g. objects with _id 1 and 3 exist but no object with _id 2. So the find method will fail. Is there a way to find all possible objects ignoring the inavlid id_s?

Upvotes: 0

Views: 2346

Answers (2)

Aren Sade
Aren Sade

Reputation: 566

Mongo first checks the length of _id and it must be 24 characters,

if one of the array members be less than 24 chars it will shows length error to you, for example:

234324533423423423423424 _id is not exists in db

 db.users.find({ '_id' :{ $in:[ObjectId("56d461517a2f02941bfb967a"),ObjectId("56d461517a2f02941bfb967e"),ObjectId("234324533423423423423424")]}}, function(err,data){})

will work perfectly to show first 2 members!

Upvotes: 0

Findiglay
Findiglay

Reputation: 976

According to the MongoDB documentation, your query should not fail where no documents exist with an id of 2.

The documentation states:

The $in operator selects the documents where the value of a field equals any value in the specified array.

Upvotes: 1

Related Questions