Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I perform an id array query in Mongoose? [duplicate]

Let's say I have a model called User. I have an array with object Ids.

I want to get all User records that "intersect" with the array of Ids that I have.

User.find({ records with IDS IN [3225, 623423, 6645345] }, function.... 
like image 891
TIMEX Avatar asked Apr 28 '11 12:04

TIMEX


People also ask

What does find by id return Mongoose?

Mongoose | findById() Function The findById() function is used to find a single document by its _id field. The _id field is cast based on the Schema before sending the command.

What is $in in Mongoose?

The value of the $in operator is an array that contains few values. The document will be matched where the value of the breed field matches any one of the values inside the array.

What is _ID in Mongoose?

From the documentation: Mongoose assigns each of your schemas an id virtual getter by default which returns the documents _id field cast to a string, or in the case of ObjectIds, its hexString.

Does find return an array Mongoose?

find returns an array always.


2 Answers

Here is a mongoosey way to use the $in operator.

User.find()   .where('fb.id')   .in([3225, 623423, 6645345])   .exec(function (err, records) {     //make magic happen   }); 

I find the dot notation quite handy for querying into sub documents.

http://mongoosejs.com/docs/queries.html

like image 94
kberg Avatar answered Sep 29 '22 10:09

kberg


You need to use the $in operator >

https://docs.mongodb.com/manual/reference/operator/query/in/#op._S_in

For example:

Users.find( { "fb" : { id: { $in : arrayOfIds } } }, callback ); 
like image 28
neebz Avatar answered Sep 29 '22 12:09

neebz