Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 425
Tyler Clendenin Avatar asked Jun 27 '18 17:06

Tyler Clendenin


People also ask

Are Mongo object IDS unique?

According to MongoDB, ObjectID can be considered globally unique. The first nine bytes in a MongoDB _ID guarantee its uniqueness across machines and processes, in relation to a single second; the last three bytes provide uniqueness within a single second in a single process.

Can we have duplicate ID in MongoDB?

If your _id values are using default ObjectIDs, the chance of collision should be extremely low. However, if you are setting custom _id values and sharding without using _id as the shard key or a prefix of the shard key, you need to guard against the possibility of creating duplicate _id values.

Are MongoDB IDS predictable?

Mongo ObjectIds are generated in a predictable manner, the 12-byte ObjectId value consists of: a 4-byte value representing the seconds since the Unix epoch, a 3-byte machine identifier, a 2-byte process id, and.

Are Mongoose IDS unique?

It does. One part of id is a random hash and another is a unique counter common accross collections.


2 Answers

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

like image 68
Roger Avatar answered Oct 02 '22 17:10

Roger


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);
like image 29
kemicofa ghost Avatar answered Oct 02 '22 16:10

kemicofa ghost