【问题标题】:How do you do a "join" on an array in mongoose (mongodb) with node.js?如何使用 node.js 在 mongoose (mongodb) 中的数组上“加入”?
【发布时间】:2011-10-13 23:03:36
【问题描述】:

您如何在 mongoose 中使用一组消息进行“加入”(我知道这不是正确的术语)?

我尝试遍历所有消息并查询以获取用户信息,但它不起作用:

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 完成的呢?

【问题讨论】:

  • 您想将消息 var 推送到新数组或内爆消息?

标签: javascript mongodb node.js


【解决方案1】:

您的代码最大的问题是,您假设代码同步运行 - 但事实并非如此。它异步运行。所以执行时消息尚未设置

 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);
  });
}

【讨论】:

  • 是的,"$in" 找到发送这些消息的用户列表,但我想不出一种简单的方法将其添加到消息中,而不是 [{message:'blah ', userId:'dsfsdf'}, ....] 它将是 [{message:'blah', user:{user info here}, ....]
  • @guy-guy 好的,乍一看没明白。编辑了我的答案。
猜你喜欢
  • 2014-09-03
  • 2019-01-11
  • 2022-01-22
  • 2012-11-03
  • 2016-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-02
相关资源
最近更新 更多