为什么我的MongooseJS ObjectIds未能通过相等性测试? [英] Why do my MongooseJS ObjectIds fail the equality test?
本文介绍了为什么我的MongooseJS ObjectIds未能通过相等性测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我按如下方式保存和检索相同的对象
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;
});
当我打印到控制台时,ObjectId是相同的.如果我在两个ObjectId上调用toString,它们是相等的.但是直接进行
When I print to the console, ObjectIds are the same. If I call toString on both ObjectIds they are equal. However doing a straight
obj1._id == obj2._id
返回false.这是怎么回事?
Returns false. What is happening here?
推荐答案
ObjectId是对象,因此标准==相等性测试将比较引用的相等性,而不是所包含的id值.比较它们的值的正确方法是将ObjectId.equals用作:
ObjectIds are objects so a standard == equality test is comparing the references for equality, not the contained id values. The right way to compare their values is to use ObjectId.equals as:
obj1.equals(obj2)
这篇关于为什么我的MongooseJS ObjectIds未能通过相等性测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文