[英]MongoDB (Node) findOne function does not return results when searching by ID
He guys, I really don't get what I'm doing wrong. 伙计们,我真的不明白我做错了什么。 Tried everything I could find on the interwebs but I can not get documents by ID in my Node application. 尝试了所有我可以在Interweb上找到的内容,但无法在Node应用程序中按ID获取文档。 So here is the situation: 因此,情况如下:
If I use the MongoDB shell in the terminal this produces: 如果我在终端中使用MongoDB shell,它将产生:
db.tochten.find({"_id" : ObjectId("577a6640c27dc10de81b265d")})
{ "_id" : ObjectId("577a6640c27dc10de81b265d"), "datum" : "2016-07-07", "weergavedatum" : "donderdag 7 juli", "begintijd" : "20:00", "eindtijd" : "21:00", "schip" : "Ouwe Dirk", "tocht" : "Rondvaart", "maxaantal" : "40", "opemerkingen" : "", "reserveringen" : [ ] }
So far so good right? 到目前为止一切都好吧?
Inside my Node app 在我的Node应用程序内部
//open db connection
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
// Set our collection
var col = db.collection('tochten');
//objectid stuff
var ObjectId = require('mongodb').ObjectID;
var o_id = new ObjectId("577a6640c27dc10de81b265d");
col.findOne({_id:o_id},function(err, docs) {
console.log("Printing docs from Array. count " + JSON.stringify(docs));
});
db.close();
});
Produces null. 产生空值。 I really breaking my head on this one. 我真的很伤脑筋。 Can someone tell me what I'm doing wrong? 有人可以告诉我我在做什么错吗?
You're closing the database before the result has arrived: 您要在结果到达之前关闭数据库:
col.findOne({_id:o_id},function(err, docs) {
console.log("Printing docs from Array. count " + JSON.stringify(docs));
});
db.close(); // <-- here!
Instead, close the database once the result has arrived: 相反, 一旦结果到达,就关闭数据库:
col.findOne({_id:o_id},function(err, docs) {
console.log("Printing docs from Array. count " + JSON.stringify(docs));
db.close();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.