I'd like to create a Mongoose Schema that validates the object below with the following restrictions:
Code example
{
field1: "data",
field2: {
type: "data",
data: "data"
}
}
Thanks in advance.
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.
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 ).
You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With