node.js mongodb select document by _id node-mongodb-native


Question

I'm trying to select a document by id

I've tried:

collection.update({ "_id": { "$oid": + theidID } }

collection.update({ "_id": theidID }

collection.update({ "_id.$oid": theidID }}

Also tried:

collection.update({ _id: new ObjectID(theidID ) }

This gives me an error 500...

var mongo = require('mongodb')
var BSON = mongo.BSONPure;
var o_id = new BSON.ObjectID(theidID );

collection.update({ _id: o_id }

None of these work. How to select by _id?

1
80
2/4/2011 9:08:19 PM

Accepted Answer

var mongo = require('mongodb');
var o_id = new mongo.ObjectID(theidID);
collection.update({'_id': o_id});
125
9/13/2015 11:28:30 AM

This the approach that worked for me.

var ObjectId = require('mongodb').ObjectID;

var get_by_id = function(id, callback) {
  console.log("find by: "+ id);
  get_collection(function(collection) {
    collection.findOne({"_id": new ObjectId(id)}, function(err, doc) {
       callback(doc);
    });
  });
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon