如果我console.log count + 1的輸出,我會得到一個正確的數字值。如果我輸出note.note_id的值,我會得到未定義的值。爲什麼是這樣?未定義的返回值
我已經嘗試將設置值設置爲函數內的預定義值。
note.note_id = db.notes.count(function(err, count) {
return count + 1;
});
如果我console.log count + 1的輸出,我會得到一個正確的數字值。如果我輸出note.note_id的值,我會得到未定義的值。爲什麼是這樣?未定義的返回值
我已經嘗試將設置值設置爲函數內的預定義值。
note.note_id = db.notes.count(function(err, count) {
return count + 1;
});
很難回答不知道什麼db.notes
是,但它似乎有什麼東西訪問數據庫。這意味着它很可能是異步的,意味着count()
方法永遠不會返回值,但您需要對回調中的結果執行任何操作。
db.notes.count(function(err, count) {
note.note_id = count + 1;
// do more stuff here
});
// do NOT do stuff here. it will run BEFORE the callback has been executed
我們需要看到更多的上下文 - 例如,db.notes.count是做什麼的?既然它是*那*函數,而不是你已經顯示的表達式中的函數,它將決定什麼'note.note_id'回來。 –
這是MongoDB的一個函數(註釋是我的集合):http://docs.mongodb.org/manual/reference/method/db.collection.count/ – Sampsa