Mongoose Schema with nested optional object with required fields

I'd like to create a Mongoose Schema that validates the object below with the following restrictions:

  • field2 is optional (0-1 relationship),
  • field2.type is required if field2 exists (notice that the name of the field is "type" as mongoose reserved word for type definitions),
  • field2 and the the base object must be in the same document.
  • Code example

    {
      field1: "data",
      field2: {
        type: "data",
        data: "data"
      }
    }
    

    Thanks in advance.


    You can refer to this answer:

    {
      field1: "your data",
      field2:
      {
        type:
        {
          "your data"
        },
        required:false
      }
    }
    

    So an example would be:

    {
      field1: String,
      field2:
      {
        type:
        {
          nestedField1:{type:String,required:true},
          nestedField2:String
        },
        required:false
      }
    }
    

    if field2 exists then nestedField1 would be required.


    你可能意思是这样的:

    var Field2Schema = new mongoose.Schema({
      type: { type: String, required: true },
      data: String
    });
    
    var MainSchema = new mongoose.Schema({
      field1: String,
      field2: Field2Schema
    });
    
    链接地址: http://www.djcxy.com/p/60694.html

    上一篇: MongoDB mongoose子文档创建两次

    下一篇: 带有必需字段的嵌套可选对象的Mongoose模式