Mongoose schema with nested optional object

Using the following diagram:

{ data1: String, nested: { nestedProp1: String, nestedSub: [String] } } 

When I do new MyModel({data1: 'something}).toObject() , the newly created document is displayed as follows:

 { '_id' : 'xxxxx', 'data1': 'something', 'nested': { 'nestedSub': [] } } 

those. the attached document is created with an empty array.

How to make "nested" completely optional, i.e. not created at all if it is not specified in the input?

I do not want to use a separate scheme for "nested" ones that do not need such complexity.

+4
source share
3 answers

The following scheme satisfies my initial requirements:

 { data1: String, nested: { type: { nestedProp1: String, nestedSub: [String] }, required: false } } 

In this case, new documents are created with a "missing" attached document, if it is not specified.

+8
source

You can use strict: false

 new Schema({ 'data1': String, 'nested': { }, }, { strict: false }); 

And then the circuit is completely optional. To set only nested as completely optional, perhaps you can do something like:

 new Schema({ 'data1': String, 'nested': new Schema({}, {strict: false}) }); 

But I never tried

+1
source

A solution without an additional Schema object can use a hook, as shown below.

 MySchema.pre('save', function(next) { if (this.isNew && this.nested.nestedSub.length === 0) { this.nested.nestedSub = undefined; } next(); }); 
0
source

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


All Articles