Comparing mongoose _id and strings


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.

11/4/2013 5:49:29 PM

Accepted 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.


7/24/2012 7:38:21 PM

ObjectIDs are objects so if you just compare them with == you're comparing their references. If you want to compare their values you need to use the ObjectID.equals method:

if (results.userId.equals(AnotherMongoDocument._id)) {

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow