Mongoose Schema with a nested optional object with required fields

I would like to create a Mongoose schema that validates the object below with the following restrictions:

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

Code example

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

Thanks in advance.

+6
source share
2 answers

You can reference 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 field 2 exists then nestedField1 will be required.

+1
source

you can keep in mind something like this:

 var Field2Schema = new mongoose.Schema({ type: { type: String, required: true }, data: String }); var MainSchema = new mongoose.Schema({ field1: String, field2: Field2Schema }); 
-1
source

Source: https://habr.com/ru/post/984491/


All Articles