【问题标题】:Mongoose Schema with nested optional object带有嵌套可选对象的猫鼬模式
【发布时间】:2016-11-09 22:37:49
【问题描述】:

使用以下架构:

{
  data1: String,
  nested: {
    nestedProp1: String,
    nestedSub: [String]
  }
}

当我new MyModel({data1: 'something}).toObject() 显示新创建的文档时,如下所示:

{
  '_id' : 'xxxxx',
  'data1': 'something',
  'nested': {
    'nestedSub': []
  }
}

即嵌套文档是用空数组创建的。

如何使“嵌套”成为完全可选的 - 即,如果输入数据中没有提供它,则根本不创建?

不想为“嵌套”使用单独的架构,不需要那种复杂性。

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    以下架构满足我原来的要求:

    {
      data1: String,
      nested: {
        type: {
           nestedProp1: String,
           nestedSub: [String]
        },
        required: false
      }
    }
    

    这样,如果未指定,新文档将使用“缺失”子文档创建。

    【讨论】:

    【解决方案2】:

    你可以使用strict: false

    new Schema({
        'data1': String,
        'nested': {
        },
    }, 
    {
        strict: false
    });
    

    然后架构是完全可选的。要仅将 nested 设置为完全可选,您可以执行以下操作:

    new Schema({
        'data1': String,
        'nested': new Schema({}, {strict: false})
    });
    

    但我从未尝试过

    【讨论】:

    【解决方案3】:

    没有额外 Schema 对象的解决方案可以使用如下钩子

    MySchema.pre('save', function(next) {
      if (this.isNew && this.nested.nestedSub.length === 0) {
          this.nested.nestedSub = undefined;
      }
      next();
    });
    

    【讨论】:

    • 很有趣,谢谢。不完全是我所希望的 - 我是在声明性模式定义之后。
    猜你喜欢
    • 2015-06-04
    • 2017-01-28
    • 1970-01-01
    • 2016-01-05
    • 2020-06-12
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 2019-07-16
    相关资源
    最近更新 更多