簡體   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