简体   繁体   English

您如何使用node.js在猫鼬(mongodb)中的数组上进行“联接”?

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

How do you do a "join" (i know it is not the correct term) with an array of messages in mongoose? 您如何与猫鼬中的一系列消息进行“联接”(我知道这是不正确的术语)?

I tried looping over all the messages and querying to get the user info but it is not working: 我尝试遍历所有消息并进行查询以获取用户信息,但是它不起作用:

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

So how is this accomplished with mongoose and node.js? 那么如何用mongoose和node.js来完成此任务?

the biggest problem with your code is, that you assume the code to run synchronously - but it doesn't. 代码的最大问题是,您假定代码可以同步运行-但事实并非如此。 it runs asynchronously. 它异步运行。 so messages is not yet set when you execute 因此执行时尚未设置消息

 console.log(messages);

do something like this instead: 做这样的事情:

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

edit ok, i see. 编辑好,我知道了。 you want to add the userInfo to the different messages. 您想要将userInfo添加到不同的消息。 easiest way to acieve this, is to use the async module: https://github.com/caolan/async 最简单的方法是使用异步模块: 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