如何等待moongose完成查询?

时间:2016-07-17 03:33:16

标签: javascript node.js mongodb asynchronous mongoose

router.post('/logout', function(req, res) {
    if(req.body.newList){
    var aux= JSON.parse(req.body.newList); 
    var aux1;
    var i=0;
    while(i<aux.length){
        aux1=aux[i];
        Task.findOne({username:aux1.username,text:aux1.text},function(err,res){
            if(res){
                i++;
            }else{
                task= new Task({username:aux1.username,text:aux1.text,state:aux1.state});
                task.save(function(err){
                    i++;
                });
            }
        });
    }
}

好吧,到目前为止,我有这个。 aux存储了一个json对象数组,它们没有_id,所以..我需要在需要时逐个遍历它们。问题是(我想)异步,因为这个代码只在数据库中保存了n次数组的最后一个元素,n是应该保存的不同元素的数量**(参见示例)。所以,我认为moongose querys的异步行为让我很头疼。可能会继续迭代等待查询结果,然后使用数组的最后一个值保存。

**例如,如果我有保存[{username:'x',text:'a'},{username:'x',text:'aa'},{username:'x',text:'aaa'}]的这些值..

保存[{username:'x',text:'aaa'},{username:'x',text:'aaa'},{username:'x',text:'aaa'}]

我尝试过使用承诺,但它没有用。可能用错了

1 个答案:

答案 0 :(得分:0)

对于这些事情,我更喜欢使用caolan's async库。只需:

npm install async添加模块。

然后用以下代码替换您的代码:

router.post('/logout', function(req, res) {
    if (req.body.newList) {
        var aux = JSON.parse(req.body.newList);
        var async = require("async");
        async.each(aux, function(aux1, callback) {

            Task.findOne({
                username: aux1.username,
                text: aux1.text
            }, function(err, res) {
                if (res) {
                    callback();
                } else {
                    task = new Task({
                        username: aux1.username,
                        text: aux1.text,
                        state: aux1.state
                    });
                    task.save(function(err) {
                        callback();
                    });
                }
            });
        }, function(err) {
            // if any of the query processing produced an error, err would equal that error
            if (err) {
                // One of the iterations produced an error.
                // All processing will now stop.
                console.log('A query failed to process');
            } else {
                console.log('All queries have been processed successfully');
                //do other things here
            }
        });
    }
});