我正在尝试使用node.js
& mongoose
将MongoDB集合中的大量文档放入数组中。在userDoc
- 循环中记录_.each
可以正常工作,但不会将它们附加到数组中。
我做错了什么? 我最好的猜测是我误解了节点的异步设计,但我不知道应该改变什么。
包含评论的代码:
returnObject.list = [];
Users.find({}, function (err, user){
_.each(user, function(userDoc){
console.log(userDoc); // Works
returnObject.list.push(userDoc); // No errors, but no users appended
});
});
console.log(returnObject); // No users here!
res.send(JSON.stringify(returnObject)); // Aint no users here either!
答案 0 :(得分:5)
啊这是一个很好的,你试图以同步风格做事:
Users.find({}, function (err, user){
// here you are iterating through the users
// but you don't know when it will finish
});
// no users here because this gets called before any user
// is inserted into the array
console.log(returnObject);
相反,你应该做这样的事情:
var callback = function (obj) {
console.log(obj);
}
Users.find({}, function (err, user){
var counter = user.length;
_.each(user, function(userDoc) {
if (counter) {
returnObject.list.push(userDoc);
// we decrease the counter until
// it's 0 and the callback gets called
counter--;
} else {
// since the counter is 0
// this means all the users have been inserted into the array
callback(returnObject);
}
});
});
答案 1 :(得分:0)
执行util.inspect(user)
以查看每个循环之前的内容。