Follow Us on Twitter

How to compare Mongo _id’s in Javascript

by Patrick Sinke on October 15, 2017 · 1 comment

When comparing MongoDB generated _id fields in Javascript, you’ll soon or later find out that the following code will not give expected results:

var id1 = mongoose.Types.ObjectId('58a0625246cb87062919eb62');
var id2 = mongoose.Types.ObjectId('58a0625246cb87062919eb62');
if (id1===id2) {
 console.log('elements are equal but we dont get here!' );
}

Although this appears a valid comparison, the console.log will never be printed. ObjectId’s are objects, and although when printed to the console appear as ordinary text, they cannot be simply compared.

A simple solution is using the .equals() function, which is part of the MongoDB driver:

var id1 = mongoose.Types.ObjectId('58a0625246cb87062919eb62');
var id2 = mongoose.Types.ObjectId('58a0625246cb87062919eb62');
if (id1.equals(id2)) {
 console.log('elements are equal' );
}

 

 

How to compare Mongo _id's in Javascript, 5.0 out of 5 based on 1 rating
Ratings:
VN:D [1.9.22_1171]
Rating: 5.0/5 (1 vote cast)

{ 1 comment… read it below or add one }

euservr October 17, 2017 at 10:03 am

Thanks for this Information. It helped me a lot.

Reply

Leave a Comment

 

Previous post:

Next post:

About Whitehorses
Company profile
Services
Technology

Whitehorses website

Home page
Whitebooks
Jobs

Follow us
Blog post RSS
Comment RSS
Twitter