Node.js 另一方面,mongodb的Find函数不能按预期的方式工作,shell也可以工作
我在mongodb中有一个名为“docs”的集合,但我无法访问itmes。我手动输入文档ID 我遵循官方文件,代码相同:Node.js 另一方面,mongodb的Find函数不能按预期的方式工作,shell也可以工作,node.js,mongodb,Node.js,Mongodb,我在mongodb中有一个名为“docs”的集合,但我无法访问itmes。我手动输入文档ID 我遵循官方文件,代码相同: var mongodb_connection_string = "mongodb://localhost:27017/docsdb"; mongo_client.connect(mongo_client.connection_string, function(err, db) { var docs_collection = db.collection('docs')
var mongodb_connection_string = "mongodb://localhost:27017/docsdb";
mongo_client.connect(mongo_client.connection_string, function(err, db) {
var docs_collection = db.collection('docs');
var cur = docs_collection.find(); // cur is undefined after this
while (cur.hasNext()) {
var el = cut.next();
console.log(el);
}
});
颊部永远不会结束,变量el也没有定义。因此,当我调用“count()”时,nodejs表示我“未定义”
虽然,我不能这样做:
db.docs.find().forEach(function(x){
self.log(x);
});
Nodejs告诉我:“TypeError:无法读取未定义的属性'find'”
更新
使用shell works进行连接:
mongo docsdb
db.docs.find()
... all the items are listed ...
参赛作品:
{"_id":"go_b0de007d-4f00-683f-c9df-2a982940e316","source":"...","location":"..."}
{"_id":"go_4ca1a326-98ca-7703-70d8-b4923cb8ad0e","source":"...","location":"..."}
{"_id":"go_7677775c-2509-33be-6f8d-1830af4adf48","source":"...","location":"..."}
{"_id":"go_4f85798c-073a-e4a0-09a4-05e6bffce488","source":"...","location":"..."}
{"_id":"go_b1eaed92-3989-076a-a32d-09e6f64a0fd4","source":"...","location":"..."}
{"_id":"go_e85c643d-4766-8649-8e56-c2e2c4b6795f","source":"...","location":"..."}
尝试解决此问题。我需要使用回调来检索结果:
my_collection.findOne( { _id: "lb_352233" }
,function(err, item)
{
...
});
你能给我看一下数据库条目吗!!您正在连接到同一个数据库吗?在node.js中,您连接到的是
docsdb
,而在shell中连接到的是mydb
。那是打字错误吗?@Jaco不,数据库名称没问题,是个错误,updated@dlopezgonzalez:您尝试过我的代码吗?@SoniPandey是的,我尝试过,请查看您的awnser.db.docs上的注释返回未定义。我只能使用“db.collections([NAME])获取集合,因此您正在获取数据,在您的问题中,您在mongo连接之前定义了docs\u集合?您正在编写mongo\u client.connection\u字符串,您应该编写mongodb\u connection\u stringI fixed,不,docs\u集合是在mongodb回调上创建的。
my_collection.findOne( { _id: "lb_352233" }
,function(err, item)
{
...
});