I have a method to find a document in my database based on its ObjectID:
console.log(\'id: \' + id + \' type: \' + typeof id);
collection.findOne
Yeah, I just spent thirty minutes baffled by this. If anyone finds themselves here, first check if you even need to convert to ObjectID in the first place. Like OP, I forgot that the hexstring is logged as just that - a hexstring.
In my case, this worked:
var myId = JSON.parse(req.body.id);
collection.findOne({'_id': ObjectID(myId)}, function(error,doc) {
if (error) {
callback(error);
} else {
callback(null, doc);
}
});
Don't forget to include at the beginning:
var ObjectId = require('mongodb').ObjectID;
Try out ObjectID(id)
instead of new ObjectID(id)
The id that was passed in to my function was already an object ID in this case, so did not need a new ObjectID to be created from it.
When ObjectIDs are logged out to the console they appear as hex strings, rather than ObjectID("hexString")
, so I thought I needed to convert it to do the find, but it was already in the format that I needed.
Try this:
var hex = /[0-9A-Fa-f]{6}/g;
id = (hex.test(id))? ObjectId(id) : id;
collection.findOne({'_id':new ObjectID(id)}, function(error,doc) {
if (error) {
callback(error);
} else {
callback(null, doc);
}
});
I was getting this because their was a space in the beginning of the id which I was using in findById method.
slice(1) removed the empty space and everything worked fine after it.
var idOfImage = req.params.id;
Campground.findById(idOfImage.slice(1), function(err, found){
if(err){
console.log(err);
}
else{
console.log(found);
res.render("show", {campground: found});
}
});