【问题标题】:What is the best way to query mongodb with mongoose with an array of IDs?使用带有 ID 数组的 mongoose 查询 mongodb 的最佳方法是什么?
【发布时间】:2017-11-02 14:24:00
【问题描述】:

我用猫鼬查询一个集合(消息)。结果是一个文档数组。每个文档都包含不同集合(用户)的 ID。现在我想从消息集合中查询每个 ID 的用户集合。 这个想法是在将用户集合中的信息返回到前端之前,用用户集合中的信息更新每个消息对象。 我尝试使用 async.each。出于某种原因,即使我确保在每次迭代后调用 callback() 函数,最终函数也不会被调用。

app.get('/getmsg', function(req, res){

 messages.find({query})
 .exec(function(err, ms){
  if(err) throw err;
  async.each(ms, function(m, callback){
   users.findOne({_id : m.userId})
    .lean()
    .exec(function(err, user){
      if(err) {
       console.log('error' , err);
       callback();
      } else {
      m.userName = user.name;

// everything is working up to here

     callback();
    }
  }), function(err){
      res.send(ms);  // this is never returned!
     }
 });
});

});

有没有更好的方法来实现这一点?我想这一定是一个常见问题。

谢谢!

【问题讨论】:

  • $in。查一下。
  • 另外messages.find({query}) 是非常错误的。这将扩展到.find({ "query": query }),您可能需要.find(query),除非您的文档中有一个名为"query" 的属性。你可能不会。
  • 只需users.find({ "_id": { "$in": ms.map( m => m.userId) } })。无需循环。对于那些懒得查的人。
  • 谢谢尼尔。我只输入'query'来表示我正在查询mongodb中的结果。真正的查询有点复杂,因为没有必要说明问题,所以遗漏了什么。我将尝试使用 $in 尤其是 map 函数来避免第二次查询的循环。

标签: node.js mongodb mongoose async.js


【解决方案1】:

您不能使用 res.send。而是创建一个函数来获取有关它的通知。像这样。

// 1st para in async.each() is the array of items
async.each(items,
// 2nd param is the function that each item is passed to
function(item, callback){
// Call an asynchronous function, often a save() to DB
item.someAsyncCall(function (){
  // Async call is done, alert via callback
  callback();
});
},
// 3rd param is the function to call when everything's done
function(err){
// All tasks are done now
doSomethingOnceAllAreDone();
}
);

【讨论】:

    猜你喜欢
    • 2021-09-23
    • 2015-10-09
    • 1970-01-01
    • 2018-06-07
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    相关资源
    最近更新 更多