nirali35
nirali35

Reputation: 53

Finding by id in MongoDB returns null

I am fairly new to NodeJS and MongoDB

I am trying to do a very basic stuff but it does not seem to be working.
I am sure that I am missing something somewhere.

Basically, I am trying to find a user from the DB based on the id.
Here is my code:

function findUser(id, cb) {
    MongoClient.connect(cs, function(err, db) {
        var col = db.collection('users');
        col.findOne({ _id: id }, function(err, user) {
            // Value of user here is always null
            // However, if I manually check the database, 
            // I can clearly see that the user with the 
            // same id does exists.
            return cb(err, user);
        });
    });
}

Upvotes: 5

Views: 6254

Answers (2)

Andrzej Żukowski
Andrzej Żukowski

Reputation: 71

I use this code:

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

app.get('/api/users/:id', function (req, res) {
    db.collection('users', function (err, collection) {
        collection.findOne({
            _id: new ObjectID(req.params.id)
        }, function (err, result) {
            res.send(result);
        });
    });
});

and it works!

Upvotes: 2

Moon
Moon

Reputation: 35265

I am assuming your id is of type string

If this is the case, you need to convert it to a proper Mongo ObjectID

Try this code:

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

function findUser(id, cb) {
    MongoClient.connect(cs, function(err, db) {
        var col = db.collection('users');
        col.findOne({ _id: new ObjectID(id) }, function(err, user) {
            return cb(err, user);
        });
    });
}

Upvotes: 7

Related Questions