Tyler Clendenin
Tyler Clendenin

Reputation: 1489

Mongo ObjectIDs not equal to eachother

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?

Upvotes: 9

Views: 9320

Answers (4)

Manish
Manish

Reputation: 1

ObjectId("507c7f79bcf86cd7994f6c0e").valueOf() === "507c7f79bcf86cd7994f6c0e" //true

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

ObjectId("507c7f79bcf86cd7994f6c0e").valueOf() === ObjectId("507c7f79bcf86cd7994f6c0e").valueOf() //true

Upvotes: -1

Roger
Roger

Reputation: 609

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

Upvotes: 5

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.

Upvotes: 0

kockburn
kockburn

Reputation: 17636

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);

Upvotes: 1

Related Questions