繁体   English   中英

如何在 Mongoose 中执行 id 数组查询?

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

假设我有一个名为User的 model 。 我有一个带有 object Id 的数组。

我想获取与我拥有的 Id 数组“相交”的所有用户记录。

User.find({ records with IDS IN [3225, 623423, 6645345] }, function....

这是使用 $in 运算符的猫鼬方式。

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

我发现点符号对于查询子文档非常方便。

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

您需要使用 $in 运算符 >

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

例如:

Users.find( { "fb" : { id: { $in : arrayOfIds } } }, callback );
User.where({ records: { $in: [3225, 623423, 6645345] } }, function ...

更多信息: http://docs.mongodb.org/manual/reference/operator/query/

对我来说,这样工作

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

Ids 是 object ids 的数组:

const ids =  [
    '4ed3ede8844f0f351100000c',
    '4ed3f117a844e0471100000d', 
    '4ed3f18132f50c491100000e',
];

带回调:

User.find().where('_id').in(ids).exec(callback);

使用异步 function:

records = await User.find().where('_id').in(ids).exec();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM