猫鼬:ObjectId比较不一致地失败 [英] Mongoose: ObjectId Comparisons fail inconsistently
问题描述
我有一个简单的工具来构建文档集合,然后自动格式化它们以进行EPUB或LaTeX渲染,该工具写在ExpressJS之上.我正在使用Coffeescript,如果那很重要(我对此表示怀疑).
I have a straightforward tool for building collections of documents and then automatically formatting them for EPUB or LaTeX rendering, written on top of ExpressJS. I'm using Coffeescript, if that matters (I doubt it).
使用猫鼬,我有以下内容:
Using Mongoose, I have the following:
DocumentSchema = new Schema
title: String
Offrefs = new Schema
ref: { type: ObjectId }
isa: String
BinderSchema = new Schema
title: String
contains: [Offrefs]
Offrefs没有指定它的含义,因为我希望能够在其他活页夹中包含一些活页夹,以创建逻辑集合:这些用于打印机",这些用于epub",这些是仅限网络"等.(我已经剔除了所有其他杂物.)
Offrefs doesn't specify what it refers to because because I want to be able to contain some binders in other binders, to create logical collections: "These are for the printer," "These are for epub," "These are web only," etc. (I've stripped out all the miscellaneous stuff out.)
不幸的是,我遇到了查询,其中检索到的对象
Unfortunately, I have run into queries where, for retrieved objects
(story._id == offref.ref) -> True
这两个确实看起来相同.但是:
And the two do indeed look the same. But:
(binder._id == offref.ref) -> False
(String(binder._id) == String(offref.ref)) -> True
对最后两个中的两个引用进行视觉比较,它们 是相同的ID号,但是ObjectId
对象无法正确比较.
And a visual comparison of the two references in the last two, they are the same ID number, but the ObjectId
objects don't compare correctly.
我不想经常进行字符串转换,当我将这些复杂的对象转换为数据树时,这很有可能.树关系在任何数据库中都是熊.他们在MongoDB中应该不难.
I don't want to have to do string conversions constantly, which is a strong possiblity when I'm converting these complex objects into trees of data. Tree relationships are a bear in any DB; they shouldn't be difficult in MongoDB.
您如何在MongoDB中比较ObjectId?
How do you do ObjectId comparisons in MongoDB?
推荐答案
直接的==
(或===
)比较将通过引用而不是值来比较两个对象.因此,只有它们都引用相同的实例时,结果才为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)
这篇关于猫鼬:ObjectId比较不一致地失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!