【问题标题】:Using a promisified mongodb to find multiple documents使用承诺的 mongodb 查找多个文档
【发布时间】:2017-02-12 08:40:48
【问题描述】:

在 node.js 服务器上工作,从我的 mongoDB 数据库中检索数据,但它变得有点笨拙,我想使用 Promise 主要是因为我以前从未使用过它们,并且希望获得洞察力,还想清理代码。我正在使用节点中的bluebird 模块来promisify mongodb,目前可以查看一项。

var client = MongoClient.connectAsync('mongodb://localhost:27017/stockData')
.then(function(db) {
  return db.collection("stockData").findOneAsync({ High:  253.41796296683228 })
})
.then(function(doc) { 
console.log(doc)
})
.catch(function(err) {
   console.log(err)
}); 

但是我希望能够使用光标循环浏览多个文档,但是我无法将整个事情都包裹起来,并且想在此处转换这段代码以使用 Promise。

MongoClient.connect(url, function(err,db){ //set up connection to mongodb takes two parameters a url for the db and a callback function 

        assert.equal(err,null) //check to see if there any errors connecting to the database
        var cursor = db.collection('stockData').find().limit(10) // cursor will be an array of objects retrieved from the database
        cursor.forEach(function(doc, err){ //loop through the cursor
            assert.equal(null,err) //check for errors
            console.log(doc)
        }, function(){ 
            db.close(); //close the database once the query is finished
        });
    });

如果您能解释发生的事情以便我能很好地处理它,我们将不胜感激。

【问题讨论】:

    标签: node.js mongodb promise


    【解决方案1】:

    我会这样做:

    var Promise = require('bluebird');
    var MongoClient = Promise.promisifyAll(require('mongodb'));
    
    MongoClient.connectAsync('mongodb://localhost:27017/test')
      .then(function (db){
        return db.collection('stockData').find({}, { limit: 10 }).toArrayAsync()
          .then(function (docs) {
            if (docs.length > 0) {
              docs.forEach(function(doc) {
                console.log(doc);
              });
            }
          })
          .catch(function (err) {
            console.log(err);
          })
          .finally(function() {
            db.close();
          })
      .catch(function (err) {
        console.log(err);
      });
    });
    

    【讨论】:

    • 您确定.connectAsync() 继续使用function (err, db) 函数吗?这正是 promises 通常不会做的事情。
    • 我按照 Luis 的方式尝试过,但是 promise 一直返回被拒绝,db 参数未定义
    • 很抱歉,我没有检查就发布了。我现在已经更新了。 @CraigHyland
    • 再次编辑。现在它起作用了。所以你需要在find 之后应用toArray 函数;在这种情况下,要使用的异步函数是 toArrayAsync() 而不是 findAsync()
    • 很抱歉这么晚才问 Luis,但为什么 findAsync() 方法中有一个空的 {}?另外,如果我想按任何顺序对查询进行排序,我是否会像使用 limit: 10 一样在 findAsync() 方法中包含排序?
    猜你喜欢
    • 2017-04-16
    • 2019-05-27
    • 2018-09-04
    • 2018-07-04
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多