【问题标题】:How to wait for a response from a mongo findOne query in a node/express app before using the response in following control flow在以下控制流中使用响应之前,如何在节点/快速应用程序中等待来自 mongo findOne 查询的响应
【发布时间】:2014-02-19 18:55:15
【问题描述】:

我是 node 新手,也是 JavaScript 回调。

我正在尝试检查 mongo 中是否存在帐户,如果不存在则“保存”,如果存在则返回错误。

我目前正试图在我的快递应用程序之外解决这个问题。这就是我所拥有的..

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/main', function (err, db) {
    if(err) throw err;

    var query = { name : "www.website.com"}

    findOne(db, query, function (doc) {
        if(doc) {
            console.log('account exists');
        } else {
            console.log('good to go');
        }
        console.dir(doc);
    });

});

var findOne = function (db, query, callback) {
    db.collection('accounts').findOne(query, function (err, doc) {
        if(err) throw err;

        db.close();

        callback();
    });
}

上面的console.dir(doc); 返回为undefined。如何等待 findOne 返回后再使用console.log 的回调或保存帐号?

【问题讨论】:

    标签: javascript node.js mongodb asynchronous callback


    【解决方案1】:

    您未定义的原因是,当您调用回调时,您没有将文档传递给它。该行应该看起来像回调(文档)。

    以下是您的代码的更新版本,其中包含一些建议:

    MongoClient.connect('mongodb://localhost:27017/main', function (err, db) {
    
        if(err) throw err;
    
        var query = { name : "www.website.com"}
    
        findOne(db, query, function (err, doc) {
            if(err) {
                // something went wrong
                console.log(err);
                return;
            }
    
            if(doc) {
                console.log('account exists');
                console.dir(doc);
            } else {
                console.log('good to go');
            }
    
        });
    
    });
    
    var findOne = function (db, query, callback) {
        db.collection('accounts').findOne(query, function (err, doc) {
    
            db.close();
    
            if(err) {
                // don't use throw when in async code
                // the convention is to call your callback with the error
                // as the first argument (notice that I added an argument 
                // to the definition of your callback above)
                callback(err);
            }
            else {
                // call your callback with no error and the data
                callback(null, doc);
            }
    
    
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2011-03-12
      • 1970-01-01
      • 2020-01-18
      • 2014-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多