2012-01-17 114 views
2

我想从一个MongoDB集合中的一些文件放入一个数组,使用node.js & mongoose。在_.each中记录userDoc -loop可以正常工作,但不会将它们追加到数组中。MongoDB从MongoDB获取数据

我在做什么错?
我最好的猜想是,我误解了一些关于节点的异步设计,但我不知道我应该改变什么。

带注释代码:

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! 

回答

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

}); 
+0

感谢您的答案和详细的例子!非常感谢 – Industrial 2012-01-18 15:42:11

+0

总是乐于帮助! – alessioalex 2012-01-18 15:46:34

0

util.inspect(user)看看你的每个循环之前有。

+0

是的 - 用户数据在那里,并显示运行时,所以我没有运行这个空集合 – Industrial 2012-01-17 18:29:23