Node.JS查询MongoDB返回null
我刚接触Node.js和MongoDB我试了一下。Node.JS查询MongoDB返回null
我做了一个名为footIco
的集合。 当我在db.footIco.find()
控制台中查询MongoDB时,它会返回所有数据。
但是,当我查询MongoDB从Node.js它不返回任何数据。
我可以在MongoDB服务器控制台中看到连接。
这是我的Node.js脚本;
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/footIco';
var findIco = function(db, callback) {
var cursor =db.collection('footIco').find();
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
} else {
callback();
console.dir(doc);
}
});
};
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
findIco(db, function() {
db.close();
});
});
有谁能告诉我这有什么问题。这几乎是从MongoDB的教程复制和粘贴
这条线:
assert.equal(err, null);
它是一个JavaScript特定的,即抛出错误处理程序将抛出行不通的,我会建议其更改为console.log(err)
或只需修改您的回调即可处理err
参数。
但是我仍然没有得到结果事件,如果我删除该部分。 – MadeInDreams
如果你没有错误,没有数据,这意味着你没有数据,你有没有用mongo控制台比如robomongo检查mongo实例? –
是的,它的工作我打电话给错误的数据库。谢谢。 – MadeInDreams
如果我使用的是良好的数据库名称,会有所帮助。 – MadeInDreams