'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?
Solution 1:[1]
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
Solution 2:[2]
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);
Solution 3:[3]
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.
Solution 4:[4]
ObjectId("507c7f79bcf86cd7994f6c0e").valueOf() === "507c7f79bcf86cd7994f6c0e" //true
ObjectId("507c7f79bcf86cd7994f6c0e") === "507c7f79bcf86cd7994f6c0e" //false
ObjectId("507c7f79bcf86cd7994f6c0e").valueOf() === ObjectId("507c7f79bcf86cd7994f6c0e").valueOf() //true
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Roger |
| Solution 2 | kemicofa ghost |
| Solution 3 | Kourosh Taheri-Golvarzi |
| Solution 4 | Mark Kvetny |
