【问题标题】:Does Mongoose only support embedded documents in arrays?Mongoose 是否只支持数组中的嵌入文档?
【发布时间】:2011-09-04 12:51:30
【问题描述】:

我在 MongoDB 中有一些如下所示的数据:

{
    name: "Steve",
    location: {
        city: "Nowhere, IL",
        country: "The United States of Awesome"
    }
}

我使用对象来组织常见的数据结构(如位置),在 Mongoose 中可能很好地映射到模式。不幸的是,它们似乎并没有真正在 Mongoose 中工作。

如果我只是嵌入一个对象,像这样:

{
    name: String,
    location: {
        city: String,
        country: String
    }
}

它似乎有效,但表现出一些奇怪的行为,这给我带来了问题(例如,instance.location.location 返回location,并且子对象从父模式继承方法)。我在猫鼬名单上started a thread,但它没有看到任何动作。

如果我嵌入一个 Schema,像这样:

{
    name: String,
    location: new Schema({
        city: String,
        country: String
    })
}

...我的应用程序没有启动(Schema 不是 Mongoose 支持的类型)。同理

{
    name: String,
    location: Object
}

……无论如何,这并不理想。

我是否遗漏了什么,或者我的架构与 Mongoose 不兼容?

【问题讨论】:

  • @Andrew 我有。你在给我看什么?我确实注意到它说,“嵌入式文档是具有自己的模式的文档,它们是其他文档的一部分(作为数组中的项目)。”这是否意味着 Mongoose 不支持像这样的模式我的?

标签: mongodb node.js mongoose


【解决方案1】:

看起来像was a bug,它已在 Mongoose 2.0 中修复!

【讨论】:

    【解决方案2】:

    我做了类似的事情:

    var Topic = new Schema({
          author    : ObjectId
        , title     : String
        , body      : String
        , topics    : [Topic]
    });
    

    这在我的测试中运行良好。但是,移除阵列支架会导致错误。对我来说似乎是一个错误。

    https://github.com/LearnBoost/mongoose/blob/master/lib/mongoose/schema.js#L185

    转储类型,我只得到 String、Number、Boolean、DocumentArray、Array、Date、ObjectId、Mixed——这似乎是故意的,schema/index.js 看起来不像是动态注册新 Schema 到类型列表,所以我猜这还不是受支持的用例。

    https://github.com/LearnBoost/mongoose/issues/188

    “嵌入单个文档是不可能的。这不是一个好主意(只需使用常规嵌套对象)”

    乔什

    【讨论】:

    • 有趣!所以看起来“常规嵌套对象”(我尝试的第一件事)也有一些损坏。我只是filed an issue
    猜你喜欢
    • 1970-01-01
    • 2012-06-08
    • 2014-01-29
    • 2013-05-17
    • 2017-02-10
    • 2011-12-14
    • 2020-06-07
    • 2022-01-08
    • 2013-03-24
    相关资源
    最近更新 更多