How to compare Mongo _id’s in Javascript
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 plaatsenReactie toevoegen