5

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);
        });
    });
}

2 Answers 2

7

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);
        });
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot Moon! I will give it a try.
2

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.