如何使用promises从mongoDB集合中打印100多个文档

时间:2016-12-01 14:10:48

标签: javascript node.js mongodb

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

当我有更多只是打印时:

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

C:\用户\ rmuntean \文件\ Automatizare \的NodeJS \ node_modules \ mongodb的\ lib中\ utils.js:98       process.nextTick(function(){throw err;});

     

TypeError:回调不是函数

我也尝试过Arr和同样的问题。

没有承诺的守则工作正常,我可以打印所有项目。

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",

我做错了什么?

1 个答案:

答案 0 :(得分:0)

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

所以你需要控制forEach何时完成,我还没有使用monogoDb,但是查看文档,如果文档为空,则表示列表的结尾。

对于承诺,请始终记住另一个then方法,如果您没有返回承诺,下一个then / finally等会在没有等待的情况下被调用,基本上打破了承诺链。

希望以下内容有所帮助。

.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);
    });
  });
})
相关问题