1
我最近開始使用異步api。現在我的要求是對3個集合 (即字段,腳本和語句)執行加入。字段可以有多個腳本,腳本可以有多個語句。async.each嵌套在async.waterfall
這裏是我到目前爲止已經試過:(加盟Fields集合使用腳本)
// Array to hold async tasks
var asyncTasks = [];
async.waterfall([
function(callback){
// fetches fields based on some Id and it returns 2 fields
db.fields.find({entity_id: mongojs.ObjectId("54440a448bbbcbb4070131ab")}, function (err, fields) {
console.log(JSON.stringify(fields, null, 2));
callback(null, fields);
})
},
function(arg1, callback){
// arg1 now equals fields
arg1.forEach(function(eachField){
asyncTasks.push(function(callback){
db.scripts.find({fieldId: eachField._id.valueOf()}, function(err, scripts) {
// Async call is done then alert via callback
console.log(JSON.stringify(scripts, null, 2));
callback(null, scripts);
});
});
});
// Now we have an array of functions doing async tasks
// Execute all async tasks in the asyncTasks array
async.parallel(asyncTasks, function(err, results) {
// All tasks are done now
console.log("Scripts" + JSON.stringify(results, null, 2));
callback(null, "done");
});
}
], function (err, result) {
console.log(result);
});
// for the above code here is what i get the output
[
{
"_id": "54440a548bbbcbb4070131ac",
"name": "t1",
"type": "String",
"entity_id": "54440a448bbbcbb4070131ab"
},
{
"_id": "54447f1d20c103981fa1a27c",
"name": "t2",
"type": "String",
"entity_id": "54440a448bbbcbb4070131ab"
}
]
size of array 2
[]
[]
Scripts[
[],
[]
]
done
以上輸出不打印任何腳本,即使有數據庫中有2個腳本。我的數據庫位於MongoDB中,我正在使用NodeJs和MongoJS api。爲什麼db.scripts.find()返回空數組? 任何幫助表示讚賞
我測試了這段代碼,看看腳本返回o/p。請在下面找到我的代碼
test2();
function test2(){
var getScriptFunction = function(eachField, doneCallback){
if(eachField !== undefined) {
var fieldId = eachField;
console.log(fieldId);
db.scripts.find({fieldId: fieldId}, function (err, result) {
// Async call is done, alert via callback
doneCallback(null, result);
});
}
}
// The array is the id of fields
async.map(["54440a548bbbcbb4070131ac", "54447f1d20c103981fa1a27c"], getScriptFunction, function (err, results) {
// Square has been called on each of the numbers
// so we're now done!
if (err){
console.log("error!" + err);
} else {
console.log("printed from helper function \n" + JSON.stringify(results, null, 2));
}
});
}
這是上面的代碼的O/P獲取腳本單獨
printed from helper function
[
[
{
"_id": "54440a678bbbcbb4070131ad",
"name": "s1",
"fieldId": "54440a548bbbcbb4070131ac"
},
{
"_id": "544af260eb7a486824a5c306",
"name": "s2",
"fieldId": "54440a548bbbcbb4070131ac"
}
],
[]
]
這是場什麼樣子(db.fields跑.find()。pretty())
[
{
"_id": "54440a548bbbcbb4070131ac",
"name": "t1",
"type": "String",
"entity_id": "54440a448bbbcbb4070131ab"
},
{
"_id": "54447f1d20c103981fa1a27c",
"name": "t2",
"type": "String",
"entity_id": "54440a448bbbcbb4070131ab"
}
]
試着將'eachField._id'直接放在你的find查詢中,而不是'eachField._id.valueOf()'。如果你給它一個真正的ObjectId實例,查詢只會匹配正確。 – 2014-11-06 10:52:23
它不會工作,因爲fieldId被保存爲字符串值而不是ObjectId。 – maddyeng 2014-11-06 16:19:37
我嘗試了你的建議,但仍然沒有運氣 – maddyeng 2014-11-06 16:36:25