【问题标题】:Nested object schema in mongoose猫鼬中的嵌套对象模式
【发布时间】:2016-04-22 21:26:45
【问题描述】:

假设我有这样的架构

var Language = new Schema({
    name: { type: String, unique: true, required: true },
    pos: [{
        name: String,
        attributes: [{
            name: String
        }]
    }]
});

posattributes 中的每个项目都有_id 吗?如果我向pos 数组中的name 字段添加唯一索引,是否会对该数组强制唯一性,还是对所有条目都是唯一的?

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    不,像 posattributes 这样没有自己架构的嵌入式文档没有 _id 属性。

    如果您向pos 数组中的name 字段添加唯一索引,则将在整个集合中强制执行唯一性,但不是在单个文档的数组中。见this post

    【讨论】:

    • 这在 Mongoose 4 中是不正确的,posattributes 将获得自己的架构。
    【解决方案2】:

    在 Mongoose 4 中,posattributes 将获得自己的架构。您可以像这样阻止他们获取 _id 属性:

    // ...
        attributes: [{
            name: String,
            _id: false
        }]
    // ...
    

    【讨论】:

      猜你喜欢
      • 2017-01-28
      • 1970-01-01
      • 2019-03-22
      • 2016-11-09
      • 2016-01-05
      • 2018-10-15
      • 2015-09-21
      • 2021-07-22
      • 2019-07-16
      相关资源
      最近更新 更多