Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Schema with nested optional object

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.

like image 722
Sunny Milenov Avatar asked Jul 07 '16 14:07

Sunny Milenov


People also ask

Which schema types are not supported by Mongoose?

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.

What does $Set do in Mongoose?

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.

What is the difference between schema and model in Mongoose?

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.

What is __ V in MongoDB?

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 ).


1 Answers

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.

like image 103
Sunny Milenov Avatar answered Sep 24 '22 23:09

Sunny Milenov