【问题标题】:Mongoose specify optional array of objectsMongoose 指定可选的对象数组
【发布时间】:2020-12-09 04:08:08
【问题描述】:

我的 mongo 集合中的一个键是

    options: [
      new mongoose.Schema(
        {
          answer: {
            type: String,
            required: true,
          },
          value: {
            type: Number,
            min: -10,
            max: 10,
            required: true,
          },
        },
        { _id: false }
      ),
    ],

我在这里遇到的问题是options 是可选的,但是当没有填写选项字段时,插入的文档有options: []

我相信我可以通过输入default: undefined 来正常解决此问题,但我不确定如何为这组对象执行此操作。

谢谢!

【问题讨论】:

    标签: mongodb mongoose mongoose-schema


    【解决方案1】:

    在 mongoose 中,空数组是数组类型的默认值。您可以通过这种方式使用default 字段来覆盖它:

    let optionsSchema = new mongoose.Schema(
        {
            answer: {
                type: String,
                required: true,
            },
            value: {
                type: Number,
                min: -10,
                max: 10,
                required: true,
            },
        },
        { _id: false });
    
    
    const RootSchema = new Schema({
        options : {
            type: [optionsSchema],
            default: undefined
        }
    })
    

    【讨论】:

    • 你太棒了!!
    猜你喜欢
    • 2019-03-25
    • 2018-07-02
    • 1970-01-01
    • 2019-04-08
    • 2014-05-13
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    相关资源
    最近更新 更多