你如何进行“加入"?在带有 node.js 的 mongoose (mongodb) 中的数组上? [英] How do you do a "join" on an array in mongoose (mongodb) with node.js?
问题描述
如何对 mongoose 中的一系列消息进行加入"(我知道这不是正确的术语)?
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
那么这是如何通过 mongoose 和 node.js 实现的?
So how is this accomplished with mongoose and 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);
改为这样做:
var userIds = [id1, id2, id3];
User.find({"_id": {$in: userIds}}, function (err, users) {
console.log(users);
});
编辑好的我明白了.您想将 userInfo 添加到不同的消息中.实现这一点的最简单方法是使用异步模块:https://github.com/caolan/async
edit ok, i see. you want to add the userInfo to the different messages. easiest way to acieve this, is to use the async module: 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);
});
}
这篇关于你如何进行“加入"?在带有 node.js 的 mongoose (mongodb) 中的数组上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!