node.js MongoDB查询未返回结果 [英] node.js MongoDB query not returning results
本文介绍了node.js MongoDB查询未返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在玩mongodb,并在用户"集合中输入了一些测试数据{name:"david"}.通过输入
I was playing around with mongodb and entered some test data {name:"david"} into the 'users' collection. I verified that the data was in MongoDB using the mongo shell by typing
db.users.find()
结果:
{ "name":"david" }
在node.js脚本中,以下代码:
In node.js script, the following code:
db.open(function(err, db) {
if (!err) {
console.log("db opened!");
}
else {
console.log(err);
}
db.collection('users', function(err, collection) {
collection.find({}, function(err, cursor) {
cursor.each(function(err, item) {
console.log(item);
});
});
});
db.close();
});
不返回任何结果
我没有发现任何错误,也没有错误返回.请指教
I don't see anything wrong, and no err returns. Please advise
推荐答案
您实际上是在从集合中返回数据之前关闭数据库连接.
You're actually closing your database connection before data from the collection has returned.
db.collection('users', function(err, collection) {
collection.find({}, function(err, cursor) {
cursor.each(function(err, item) {
console.log(item);
});
// our collection has returned, now we can close the database
db.close();
});
});
这篇关于node.js MongoDB查询未返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文