为什么我的 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;
});
当我打印到控制台时,ObjectIds 是相同的.如果我在两个 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
返回假.这里发生了什么?
Returns false. What is happening here?
推荐答案
ObjectIds 是对象,因此标准 == 相等性测试是比较引用的相等性,而不是包含的 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屋!
查看全文