Mongoose 指定可选的对象数组

Dan*_*ssa 5 mongoose mongodb mongoose-schema

我的 mongo 收藏中的关键之一是

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

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

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

谢谢!

mic*_*ckl 7

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

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
    }
})
Run Code Online (Sandbox Code Playgroud)