Why are my MongooseJS ObjectIds not passing an equality check?

Suppose I save and retrieve identical objects as follows

var obj1, obj2; instance.save(function(err, saved) { obj1 = saved; }); Model.find(obj1._id).run(function(err, retrieved) { obj2 = retrieved; }); 

When I print to the console, ObjectIds are the same. If I call toString for both ObjectIds, they are equal. However making a direct

 obj1._id == obj2._id 

Returns false. What's going on here?

+8
mongodb mongoose
source share
1 answer

ObjectIds are objects, so the standard equality criterion compares references for equality, rather than the contained id values. The correct way to compare their values ​​is to use ObjectId.equals like:

 obj1.equals(obj2) 
+19
source share

All Articles