【发布时间】:2014-09-04 01:00:49
【问题描述】:
我有一组具有唯一 _id 的文档,我想将它们插入到我的数据库中。其中一些已经在数据库中,对于那些我想更新数组属性的人(将数组推入一个项目)。所有这一切我都需要异步进行,所以在所有插入/更新之后,我想将响应写回(带有回调)给客户端,而不是一切正常或写一个错误。在搜索主题后,我发现了这个solution with async module 我试图为我的案例实现它。现在我的代码如下所示:
function processUsers(arr, listName, callback) {
var users = global.db.collection('vkusers');
var q = async.queue(function(task, cb) {
console.log('upsert butch');
users.insert(task.doc, function(err, doc) {
if (err) {
users.update({
_id : task.doc._id
}, {
$addToSet : {
mLists : listName
}
}, function(error, result){ console.log(error); console.log(result); });
}
});
}, arr.length);
for ( var doc in arr) {
q.push({
doc : arr[doc]
}, function(err) {
if (err)
callback(err, null);
})
}
q.drain = function() {
// this is the queue's callback, called when the queue is empty,
// i.e. when all your documents have been processed.
console.log('drain');
callback(null, { result: "success", upserted: arr.length });
}
}
回调有签名回调(错误,结果),arr - 我的文档数组。我已经对其进行了测试,并且使用数据库一切正常,我得到了正确的结果。但是回调和 q.drain 从未触发!
【问题讨论】:
标签: node.js mongodb asynchronous