Mongoose:ObjectId 比较失败不一致 [英] Mongoose: ObjectId Comparisons fail inconsistently

查看:34
本文介绍了Mongoose:ObjectId 比较失败不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的工具来构建文档集合,然后自动格式化它们以用于 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?

推荐答案

直接的 ==(或 ===)比较将通过引用比较两个对象,不值.因此,只有当它们都引用相同的实例时,才会评估为真.

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的code>equals方法比较它们的值:

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

story._id.equals(offref.ref)

正如@bendytree 在评论中指出的那样,如果任何一个值都可以为空(并且您希望空值比较相等),那么您可以改用以下内容:

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)

这篇关于Mongoose:ObjectId 比较失败不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆