Node.js – Comparing mongoose _id and strings

mongodbmongoosenode.js

I have a node.js application that pulls some data and sticks it into an object, like this:

var results = new Object();

User.findOne(query, function(err, u) {
    results.userId = u._id;
}

When I do an if/then based on that stored ID, the comparison is never true:

if (results.userId == AnotherMongoDocument._id) {
    console.log('This is never true');
}

When I do a console.log of the two id's, they match exactly:

User id: 4fc67871349bb7bf6a000002 AnotherMongoDocument id: 4fc67871349bb7bf6a000002

I am assuming this is some kind of datatype problem, but I'm not sure how to convert results.userId to a datatype that will result in the above comparison being true and my outsourced brain (aka Google) has been unable to help.

Best Answer

Mongoose uses the mongodb-native driver, which uses the custom ObjectID type. You can compare ObjectIDs with the .equals() method. With your example, results.userId.equals(AnotherMongoDocument._id). The ObjectID type also has a toString() method, if you wish to store a stringified version of the ObjectID in JSON format, or a cookie.

If you use ObjectID = require("mongodb").ObjectID (requires the mongodb-native library) you can check if results.userId is a valid identifier with results.userId instanceof ObjectID.

Etc.