【问题标题】:How can I Promisify Node's mongodb module for cursors and/or a collections' toArray() using Bluebird?如何使用 Bluebird 为游标和/或集合的 toArray() Promisify Node 的 mongodb 模块?
【发布时间】:2014-10-07 11:40:30
【问题描述】:

相关包:

"dependencies": {
  "mongodb":    "1.4.x",
  "bluebird":   "2.3.x"
}

我看过:

findAsync({}) 之后我被卡住了。

更喜欢一个游标,但很少有太多东西可以调用toArray()

也有可能我做错了。

MongoClient.connectAsync('mongodb://127.0.0.1:27017/sr')
  .then(function(_db) {
    db = _db;
    return db.collectionAsync('posts');
  })
  .then(function(colPosts) {
    return colPosts.findAsync({});
  })
  .then ( A MIRACLE OCCURS )
  .catch(function(e) {
    console.log(e);
  })
  .finally(function() {
    if (db) db.close();
  });

奇迹发生的地方我想遍历游标结果或数组化集合。我在弄清楚如何解决这个问题时遇到了问题。

【问题讨论】:

标签: javascript node.js promise node-mongodb-native bluebird


【解决方案1】:

据我了解,.findAsync 返回一个游标的承诺。如果您想将数据拉入内存(如.toArray),我认为您正在寻找的内容类似于:

MongoClient.connectAsync('mongodb://127.0.0.1:27017/sr')
  .then(function(_db) {
    db = _db;

    return db
      .collection('posts')
      .find({})
      .limit(limit)
      .sort(sort)
      .toArrayAsync();
  })
  .then(function(posts) {
    console.log('posts', posts);
  })
  .catch(function(e) {
    console.log(e);
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 2020-12-05
    • 2015-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多