我如何通过承诺从MongoDB收藏中打印100多个文档



i只需打印集合中的所有项目。我正在使用此代码,并且在收藏集中的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 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",

我在做什么错?

由于您的foreach没有返回诺言,因此finally立即被称为IOW:theDb.close()在您甚至有机会迭代结果之前被调用。这解释了undefined

因此,您需要控制何时完成foreach,我没有使用monogodb,但是查看文档,如果文档为空,则意味着列表的结尾。

有了承诺,请始终从另一种then方法中记住,如果您不返回承诺,下一个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);
    });
  });
})

最新更新