簡體   English   中英

您如何使用node.js在貓鼬(mongodb)中的數組上進行“聯接”?

[英]How do you do a “join” on an array in mongoose (mongodb) with node.js?

您如何與貓鼬中的一系列消息進行“聯接”(我知道這是不正確的術語)?

我嘗試遍歷所有消息並進行查詢以獲取用戶信息,但是它不起作用:

messages.forEach(function (message, index) {
  User.findById(message.userId, function (err, user) {
    messages[index].user = user
  })
})

console.log(messages) // the user info is not attatched

那么如何用mongoose和node.js來完成此任務?

代碼的最大問題是,您假定代碼可以同步運行-但事實並非如此。 它異步運行。 因此執行時尚未設置消息

 console.log(messages);

做這樣的事情:

var userIds = [id1, id2, id3];
User.find({"_id": {$in: userIds}}, function (err, users) {
  console.log(users);
});

編輯好,我知道了。 您想要將userInfo添加到不同的消息。 最簡單的方法是使用異步模塊: https : //github.com/caolan/async

async.map(messages, getUserInfo, function (err, result) {
  if (err) {
    console.log(err);
    return;
  }
  // log all msg with userinfo
  console.log(result);
});

function getUserInfo (msg, callback) {
  User.findById(msg.userId, function (err, user) {
    if (err) {
       callback(err);
       return;
    }
    msg.user = user;
    callback(null, msg);
  });
}

暫無
暫無

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

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