【问题标题】:Making butch upsert in mongodb: callback never fired在 mongodb 中制作 butch upsert:回调从未触发
【发布时间】: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


    【解决方案1】:

    插入/更新完成后,您需要调用async.queue 的回调(代码中的cb)。像这样的:

    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); 
    
                    cb(error); // Update finished; call cb and pass in "error" so that it can bubble up if it exists
                });
            } else {
                cb(); // Insert succeeded; call cb
            }
        });
    
    }, arr.length);
    

    【讨论】:

      猜你喜欢
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      • 2011-02-12
      • 2020-08-08
      • 1970-01-01
      • 2019-02-04
      • 1970-01-01
      相关资源
      最近更新 更多