【问题标题】:How can I print more than 100 documents from mongoDB collection with promises如何使用承诺从 mongoDB 集合中打印 100 多个文档
【发布时间】:2017-04-16 05:13:11
【问题描述】:

我只打印集合中的所有项目。我正在使用此代码,并且在集合中少于 100 个项目的情况下工作正常。

当我有更多的时候只是打印:

ITEMS: undefined
1
ITEMS: undefined
2
.....
ITEMS: undefined
99
ITEMS: undefined
100
ITEMS: undefined

C:\Users\rmuntean\Documents\Automatizare\NodeJS\node_modules\mongodb\lib\utils.js:98 process.nextTick(function() { throw err; });

TypeError:回调不是函数

我也试过 toArray 并且是同样的问题。

没有承诺的代码运行良好,我可以打印所有项目。

var bluebird = require('bluebird');
var MongoClient = require('mongodb').MongoClient;
var MongoCollection = require('mongodb').Collection;

bluebird.promisifyAll(require('mongodb'));

const connection = "mongodb://localhost:27017/test";

var cc = 0;
var theDb
var theCollection

MongoClient.connectAsync(connection)
  .then(function(db) {
    theDb = db;
    return theDb.collectionAsync("test_array");
  })
  .then(function(collection) {
    theCollection = collection;
    return theCollection.findAsync({});
  })
  .then(function(cursor) {
    cursor.forEach((err, items) => {
      console.log("ITEMS:", items);
      cc++
      console.log(cc);
    });
  })
  .finally(() => {
    theDb.close()
  })
  .catch((err) => {
    console.log(err);
    err(500);
  });

我正在使用:

"mongodb": "^2.2.12",
"bluebird": "^3.4.6",

我做错了什么?

【问题讨论】:

  • cursor.forEach((err, items) 你在这里没有返回任何东西,所以你的 finally 会立即被调用。您可以将 forEach 包装在 Promise 中,因为我相信所有完成的项目 items 都将是错误的。

标签: javascript node.js mongodb


【解决方案1】:

因为你的 forEach 没有返回一个承诺,finally 被立即调用,IOW: theDb.close() 在你甚至有机会迭代结果之前就被调用了。这解释了undefined

所以你需要控制forEach什么时候结束,我没用过monogoDb,但是看文档,如果文档是空的,就意味着列表结束。

有了promise,永远记住从另一个then方法内部,如果你不返回一个Promise,下一个then/finally等会在没有等待的情况下被调用,你基本上已经破坏了promise链。

所以希望以下内容会有所帮助。

.then(function(cursor) {
  return new Promise((resolve, reject) => {
    cursor.forEach((err, items) => {
      if (err) return reject(err);
      if (!items) return resolve(); //no more items
      console.log("ITEMS:", items);
      cc++
      console.log(cc);
    });
  });
})

【讨论】:

  • 谢谢您,我使用了您的建议和代码并且正在工作:.then(function(cursor) { return new Promise((resolve, reject) => { cursor.each((err,items) => { if (cursor.isClosed()) return resolve(); console.log("ITEMS:", items); cc++ console.log(cc); }); }); })
猜你喜欢
  • 1970-01-01
  • 2014-09-08
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-21
  • 1970-01-01
  • 2011-07-18
相关资源
最近更新 更多