且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

猫鼬:ObjectId比较不一致地失败

更新时间:2023-02-13 13:54:55

直接的==(或===)比较将通过引用而不是值来比较两个对象.因此,只有它们都引用相同的实例时,结果才为true.

A straight == (or ===) comparison will compare the two objects by reference, not value. So that will only evaluate to true if they both reference the very same instance.

相反,您应该使用 ObjectID的c3> 方法比较它们的值:

Instead, you should be using the equals method of ObjectID to compare their values:

story._id.equals(offref.ref)

正如@bendytree在注释中所指出的那样,如果两个值中的任何一个都可以为null(并且您希望null与相等值进行比较),则可以改用以下内容:

As @bendytree notes in the comments, if either value could be null (and you want nulls to compare as equal), then you can use the following instead:

String(story._id) === String(offref.ref)