我有一个 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){ });
}
});
}
});
}
});
所以我只是使用回调来使用嵌套调用,并在某种程度上使其同步。我是否有机会并行执行所有这三个查找查询,然后执行保存命令?我实际上想利用 Node.js 的异步特性。有什么建议吗?
最佳答案
如果您不想包含外部库,您可以自己构建类似 async.parallel
的内容。下面是一个简单的并行
函数的样子。实现 async 库中的其他函数可能是一个很好的练习。
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
});
});
关于javascript - 使用 mongodb 保存具有 Node.js 异步特性的多个数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23996585/