icon-arrow icon-check icon-mail icon-phone icon-facebook icon-linkedin icon-youtube icon-twitter icon-cheveron icon-download icon-instagram play close close icon-arrow-uturn icon-calendar icon-clock icon-search icon-chevron-process icon-skills icon-knowledge icon-kite icon-education icon-languages icon-tools icon-experience icon-coffee-cup
Werken bij Integration & Application Talents
Blog 15/10/2017

How to compare Mongo _id’s in Javascript

balance

When comparing MongoDB generated _id fields in Javascript, you’ll soon or later find out you cannot simply compare them as if they are plain text variables. The following code will not give the 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' );
}

 

Geen reacties

Geef jouw mening

Reactie plaatsen

Reactie toevoegen

Jouw e-mailadres wordt niet openbaar gemaakt.

Geen HTML

  • Geen HTML toegestaan.
  • Regels en alinea's worden automatisch gesplitst.
  • Web- en e-mailadressen worden automatisch naar links omgezet.

Wil je deel uitmaken van een groep gedreven en ambitieuze experts? Stuur ons jouw cv!