簡體   English   中英

MongoDB中具有數組的查詢模型

[英]Query model with array in mongodb

我是Node和MongoDB的新手。

我正在嘗試使用數組查詢模型。

數組看起來像這樣

 var grArr =  [ '5aabc39a3d88101e4b52c861', '5ac3a1fe83d45353bc6a995c' ]

和查詢是

Group.find().where({ _id: { $in: grArr }}).exec(function(err,gdoc){
      if(err)
      {
         callback({err:err,message:"Error looking up company"});
      }
      else
      {
         console.log(gdoc.companies); //Gives undefined
         callback(null,gdoc.companies);
      }
});

查詢返回undefined

非常感謝您的幫助。

有兩種用貓鼬執行查詢的方法,在我看來,您正在混合使用這兩種方法。

  • Find應該以您的查詢作為參數來調用:

你會得到類似

Group.find({ _id: { $in: grArr }}, function(err,gdoc){
      if(err) {
         callback({err: err, message:"Error looking up company"});
      }
      else {
         console.log(gdoc); //Should print all the matching documents since gdoc is an array
         callback(null, gdoc.map(doc => doc.companies); //returns every companies of every document
      }
});

這次您可以調用不帶任何參數的Find並像這樣鏈接where語句

Group.find({}).where('_id').in(grArr).exec(callback)

find()將數組傳遞給回調函數。 請參閱文檔https://mongoosejs.com/docs/api.html#model_Model.find

gdoc是數組。 像這樣編輯代碼:

...
callback(null, gdoc[0].companies);
...

嘗試這個,

Group.find({ _id: { $in:arr }).lean().exec().then((result) => {

}, (err) => {

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM