Mongo ObjectIDs not equal to eachother
Asked Answered
M

4

8
new Mongo.ObjectID('18986769bd5eaaa42cb565b1') == new Mongo.ObjectID('18986769bd5eaaa42cb565b1')

returns false

new Mongo.ObjectID('18986769bd5eaaa42cb565b1').toString() == new Mongo.ObjectID('18986769bd5eaaa42cb565b1').toString()

returns true

Is this a bug, a feature or do I need to only work with these using valueOf() and convert it back from string when I need to work with the database?

Mangosteen answered 27/6, 2018 at 17:4 Comment(4)
Two separate JavaScript objects are never == to each other.Boustrophedon
You should take a look at this question, it might solve yours #11637853 Basically they say that you need to use the equals method provided by the mongo library you are usingPhiladelphia
@Roger, please add your comment as an answer so I can accept it.Mangosteen
@TylerClendenin Done!Philadelphia
P
5

You should take a look at this question, it might solve yours. Basically, they say that you need to use the equals method provided by the mongo library you are using

Philadelphia answered 11/7, 2018 at 5:1 Comment(0)
P
1

This is completely normal as two objects are not equal to each other even if they contain the same information. You need to loop through all the properties and compare them individually.

console.log({} === {});

example

const obj1 = {id: 12345}
const obj2 = {id: 12345}

console.log(obj1 === obj2);

let same = true;
for(const prop in obj1){
  if(obj2.hasOwnProperty(prop) && obj1[prop] !== obj2[prop]){
      same = false;
      break;
  }
}

console.log(same);
Philan answered 27/6, 2018 at 17:7 Comment(0)
C
0

It's because MongoDB is entirely based around JSON, so even if a particular piece of information is itself a string, Mongo still delivers it as a JSON object. Therefore, you need to parse it back into string form so that you can use it somewhere else.

Cursory answered 27/6, 2018 at 17:29 Comment(0)
A
-1
ObjectId("507c7f79bcf86cd7994f6c0e").valueOf() === "507c7f79bcf86cd7994f6c0e" //true

ObjectId("507c7f79bcf86cd7994f6c0e") === "507c7f79bcf86cd7994f6c0e" //false

ObjectId("507c7f79bcf86cd7994f6c0e").valueOf() === ObjectId("507c7f79bcf86cd7994f6c0e").valueOf() //true
Ashanti answered 8/4, 2022 at 10:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.