【发布时间】: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