Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying a MongoDB based on Mongo ID in a node.js app

I'm using a node.js and mongodb, and I'm trying to query the database based on the mongo generated ID using the following:

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

I am 100% certain that my doc._id is an exact match to the doc _id that I am looking for in the collection, and yet I get a null response from the db query.

I have tried this using other keys in the document and it returns the document just fine. It's only when I try to use the mongo ID.

like image 783
user699242 Avatar asked Oct 07 '12 13:10

user699242


People also ask

How fetch data from MongoDB by id in node JS?

connect('mongodb://localhost/Company'); var Schema = new mongoose. Schema({ _id : String, name: String, age : Number }); var user = mongoose. model('emp', Schema); app. param('id', function(req, res, next, id){ user.

How does MongoDB connect to node js application?

To create a database in MongoDB, start by creating a MongoClient object, then specify a connection URL with the correct ip address and the name of the database you want to create. MongoDB will create the database if it does not exist, and make a connection to it.

What is the use of ID in MongoDB?

Every document in the collection has an “_id” field that is used to uniquely identify the document in a particular collection it acts as the primary key for the documents in the collection. “_id” field can be used in any format and the default format is ObjectId of the document.


2 Answers

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

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

This converts my string into a mongo ObjectId and matches the _id in the db!

like image 59
user699242 Avatar answered Sep 30 '22 00:09

user699242


Following is the example which spots the issue:

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)); 
        });
  });
});
like image 34
Amol M Kulkarni Avatar answered Sep 30 '22 00:09

Amol M Kulkarni