我有这段代码
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://user:pwd@lo037234.mlab.com:37234/heroku_plpzj3t5j';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
db.collection('members', function(err, collection) {
collection.find({}, function(err, cursor) {
cursor.each(function(err, item) {
console.log(item.telephoneNumber);
});
// our collection has returned, now we can close the database
db.close();
});
});
});
我用来列出集合成员中的所有电话号码。
然而,代码列出了数字,然后显示这样的错误
Connected correctly to server
0820069005
0920069005ww
0220929975
/home/obulex/node_modules/mongodb/lib/utils.js:98
process.nextTick(function() { throw err; });
^
TypeError: Cannot read property 'telephoneNumber' of null
at /home/obulex/workers/actors/actor.js:14:23
at handleCallback (/home/obulex/node_modules/mongodb/lib/utils.js:96:12)
at /home/obulex/node_modules/mongodb/lib/cursor.js:741:16
at handleCallback (/home/obulex/node_modules/mongodb/lib/utils.js:96:12)
at /home/obulex/node_modules/mongodb/lib/cursor.js:675:5
at handleCallback (/home/obulex/node_modules/mongodb-core/lib/cursor.js:172:5)
at setCursorDeadAndNotified (/home/obulex/node_modules/mongodb-core/lib/cursor.js:507:3)
at nextFunction (/home/obulex/node_modules/mongodb-core/lib/cursor.js:651:7)
at Cursor.next [as _next] (/home/obulex/node_modules/mongodb-core/lib/cursor.js:692:3)
at nextObject (/home/obulex/node_modules/mongodb/lib/cursor.js:672:8)
为什么我在代码结尾处收到错误?
答案 0 :(得分:0)
问题是您的代码在find()方法中执行回调。
根据API,collection.find()返回一个Cursor对象: http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#find
根据上面链接中显示的一些示例或下面链接的教程尝试重构代码: https://docs.mongodb.com/getting-started/node/query/#query-for-all-documents-in-a-collection
正如Henrique所说,由于原始提交中包含的敏感信息,您可能希望删除此问题。
答案 1 :(得分:0)
这终于奏效了
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://logan:password32@username32.mlab.com:37234/heroku_xpzj3t5j';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
var cursor = db.collection('members').find( );
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.log(doc.telephoneNumber);
} else {
//callback();
}
});
});