Using the following schema:
{
data1: String,
nested: {
nestedProp1: String,
nestedSub: [String]
}
}
When I do new MyModel({data1: 'something}).toObject()
shows the newly created document like this:
{
'_id' : 'xxxxx',
'data1': 'something',
'nested': {
'nestedSub': []
}
}
I.e. the nested document is created with the empty array.
How do I make "nested" to be fully optional - i.e. not created at all if it is not provided on the input data?
I do not want to use a separate schema for the "nested", no need of that complexity.
Mongoose does not natively support long and double datatypes for example, although MongoDB does. However, Mongoose can be extended using plugins to support these other types.
The $set operator replaces the value of a field with the specified value. The $set operator expression has the following form: { $set: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.
A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.
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 ).
The following schema satisfies my original requirements:
{
data1: String,
nested: {
type: {
nestedProp1: String,
nestedSub: [String]
},
required: false
}
}
With this, new docs are created with "missing" subdocument, if one is not specified.
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