Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 924
Víctor Herraiz Avatar asked Mar 31 '15 10:03

Víctor Herraiz


People also ask

What is required true in Mongoose schema?

Mongoose has several built-in validators. All SchemaTypes have the built-in required validator. The required validator uses the SchemaType's checkRequired() function to determine if the value satisfies the required validator. Numbers have min and max validators.

What is __ V 0 in Mongoose?

The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero ( __v:0 ).

Can I set default value in Mongoose schema?

You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.


1 Answers

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.

like image 135
Mina Michael Avatar answered Sep 27 '22 17:09

Mina Michael