2012-01-17 116 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