10

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.

Sunny Milenov
  • 21,990
  • 6
  • 80
  • 106

3 Answers3

29

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.

Sunny Milenov
  • 21,990
  • 6
  • 80
  • 106
  • Warning: this is not valid schema in Mongoose. It may have been when this answer was written, but it is not in current versions. See https://github.com/Automattic/mongoose/issues/8107 – Tommy May 06 '21 at 04:55
1

You can use strict: false

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

And then the schema is fully optional. To set only nested as fully optional maybe you can do something like:

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

But I have never tried

Mikel
  • 361
  • 1
  • 9
0

A solution without additional Schema object could use a hook like the following

MySchema.pre('save', function(next) {
  if (this.isNew && this.nested.nestedSub.length === 0) {
      this.nested.nestedSub = undefined;
  }
  next();
});
DAXaholic
  • 33,312
  • 6
  • 76
  • 74