Dirk Dirk - 5 months ago 25
Node.js Question

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. So here is the situation:

If I use the MongoDB shell in the terminal this produces:

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

//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?

Answer

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();
});