Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in SQL by (47.6k points)

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 data type that will result in the above comparison being true and my outsourced brain (aka Google) has been unable to help.

1 Answer

0 votes
by (106k points)

Mongoose_id uses the mongodb-native driver and that driver uses the custom ObjectID type. You can compare ObjectIDs with the .equals() method. With your example, results.userId.equals(AnotherMongoDocument._id)

Where as 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 it requires the mongodb-native library and you can check if results.userId is a valid identifier with results.userId instanceof ObjectID.

Browse Categories