7
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?

Tyler Clendenin
  • 1,459
  • 1
  • 12
  • 25

4 Answers4

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

Roger
  • 579
  • 4
  • 13
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);
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
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.

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

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

ObjectId("507c7f79bcf86cd7994f6c0e").valueOf() === ObjectId("507c7f79bcf86cd7994f6c0e").valueOf() //true
Mark Kvetny
  • 664
  • 6
  • 19
Manish
  • 1
  • 1