用mongodb保存node.js的asynchronous性质的多个数据

我有一个ID数组:

var ids = ['53asd3','53asd2','53asd5']; 

每个id在mongodb中都有相应的文件。 我想通过填充每个对象的数据来生成一个对象,并保存在其他文档中。 喜欢这个:

 { person: { /* data from some collection populated with first id */}, company : { /* data from some collection populated with first id */}, employee : {/* data from some collection populated with first id */} } 

我做了什么

 var document = {} models.persons.find({_id:'53asd3'},function(err,data){ if(!err) { document['persons']=data; models.company.find({_id:'53asd2'},function(err,data){ if(!err) { document['company']=data; models.employee.find({_id:'53asd2'},function(err,data){ if(!err) { document['employee']=data; document.save(function(err){ }); } }); } }); } }); 

所以我只是使用callback使用嵌套的调用,并有点使它同步。 有没有机会可以同时执行所有这三个查询查询,然后执行保存命令? 我其实想要利用node.js的asynchronous性质 有什么build议么?

如果你不想包含外部库,你可以自己构build一些类似async.parallel东西。 以下是一个简单的parallel函数的样子。 在async库中实现其他function可能是一个很好的练习。

 var parallel = function () { var functs = arguments[0]; var callback = arguments[1]; // Since we're dealing with a sparse array when we insert the results, // we cannot trust the `length` property of the results. // Instead we count the results separately var numResults = 0; var results = []; var getCallback = function (i) { return function (err, res) { if (err) { callback(err) } else { results[i] = res; numResults += 1; if (numResults === functs.length) { callback(null, results); } } } } functs.forEach(function (fn, i) { fn(getCallback(i)); }); }; var getTest = function (timeout) { return function (callback) { setTimeout(function () { callback(null, timeout); }, timeout); } }; parallel([getTest(99), getTest(1000), getTest(199)], console.log.bind(console)); >> null [99, 1000, 199] 

那么在你的情况下,你可以做类似的事情

 var findItem = function (collection, id) { return function (callback) { collection.find({ _id: id }, callback); }; }; parallel([ findItem(models.persons, '53asd3'), findItem(models.company, '53asd2'), findItem(models.employee, '53dsa2') ], function (err, results) { document.persons = results[0]; document.company = results[1]; document.employee = results[2]; document.save(function (err) { // and so on }); });