MongoDB query based on Mongo id in node.js application

I am using node.js and mongodb and I am trying to query the database based on the mongo generated identifier using the following:

collection.findOne( {_id:doc._id} , function(err, item) {}); 

I am 100% sure that my doc._id is an exact match with the doc _id that I am looking for in the collection, but still get a null response from the db request.

I tried this using other keys in the document and it returns the document perfectly. This is only when I try to use the mongo identifier.

+8
mongodb
source share
4 answers

MongoDb is an object, not a string. To convert my string, I used:

  var id = require('mongodb').ObjectID(doc._id); 

This converts my string to Mongo ObjectId and maps _id to db!

+12
source share

Use this:

 ObjectId = require('mongodb').ObjectID; 

Then, when you try to find an object in the collection using _id, use this:

  console.log("find by: "+ id); database.collection("userRegister").findOne({_id: new ObjectId(id)}, function(err, res) { if (err) console.log(err); if(res!=null){ console.log(res) return false; } if(res==null){ callback({'status':_error,'flag':'notexist','message':_userNotExist}); return false; } }); 
+10
source share

The following is an example that indicates a problem:

 var mongo = require('mongodb'), Server = mongo.Server, Db = mongo.Db, ObjectID = require('mongodb').ObjectID; var MongoClient = require('mongodb').MongoClient //let id = your _id, smth like '6dg27sh2sdhsdhs72hsdfs2sfs'... var obj_id = new ObjectID('52cbd028e9f43a090ca0c1af'); var justId = '52cbd028e9f43a090ca0c1af'; // <== This will not work MongoClient.connect('mongodb://127.0.0.1:27017/YourDbName', function(err, db) { console.log('err' + err); db.collection('YourCollectionName', function(error, collection) { //collection.find({_id:justId}),function(err, docs) { // <== This will not work collection.findOne({_id:obj_id},function(err, docs) { console.log("Printing docs from Array. count " + JSON.stringify(docs)); }); }); }); 
+9
source share

First, make sure you add all the necessary modules to your MongoDB configuration:

 var mongo = require('mongodb'), Server = mongo.Server, Db = mongo.Db, ObjectID = require('mongodb').ObjectID; var BSON = require('mongodb').BSONPure; var server = new Server('localhost', 27017, { auto_reconnect: true }); var db = new Db('YOUR_DB_NAME', server); 

Then, when you try to find an object in the collection using _id, use:

 //let id = your _id, smth like '6dg27sh2sdhsdhs72hsdfs2sfs'... var obj_id = BSON.ObjectID.createFromHexString(id); db.collection("NAME_OF_COLLECTION_WHERE_IS_YOUR_OBJECT", function(error, collection) { collection.findOne( {_id:obj_id} , function(err, item) { // console.log ( item.username ); }); }); 

Hope this works.

+1
source share