How do I perform an id array query in Mongoose?

2019-01-22 18:07发布

问题:

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....

回答1:

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 );


回答2:

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



回答3:

User.where({ records: { $in: [3225, 623423, 6645345] } }, function ...

more info here: http://docs.mongodb.org/manual/reference/operator/query/



回答4:

For me, work this way

IDs=["5b00c4b56c7fb80918293dd9","5b00c4b56c7fb80918293dd7",...]
const users= await User.find({records:IDs})