Mongoose is the most widely schema-based solution to model your application data in MongoDB. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.
A record in MongoDB is a document, which is a data structure composed of field and value pairs. MongoDB documents are similar to JSON objects. The values of fields may include other documents, arrays, and arrays of documents. Subdocuments are documents embedded in other documents. In Mongoose, this means you can nest schemas in other schemas. However; nested paths are subtly different from subdocuments.
Sub-documents and Nested documents
Let us take a describe a schema of a person as below:
In the above model:
profilefield is defined as a sub-document schema
othersfield is defined as a nested document
friendsis an array of names defined as nested document
hobbiesis an array of hobbies defined as sub-document
Let us now try to understand the subtle difference between sub-document and nested document.
Subdocument paths are
undefined by default, and Mongoose does not apply subdocument defaults unless you set the subdocument path to a non-nullish value.
Now let us look at below code and understand the difference in arrays as well
Mongoose adds an
_id field to subdocuments by default. It can be disabled by setting the
_id option to false in sub-document definition
_id field in the single nested document
A field e.g.
friends with an array of objects, Mongoose automatically convert the object to a schema and hence
_id field is added by default. It can be disabled as stated above.
However; if we set
mongoose.Schema.Types.DocumentArray.set('_id', false); in the schema definition; array fields differ a bit. Array field with sub-document objects still has
_id added as shown below
Preferred way to define schema
In my personal opinion; embedded documents should follow sub-document schema definition. I also prefer to disable default auto addition of
_id field. Sub-documents schemas can have middleware, custom validation logic, virtuals, and any other feature top-level schemas can use. Also, validations in nested objects is tricky as they are not fully fledged paths.
There is subtle difference between sub-document and nested document in Mongoose. In my personal view sub-document schema definition should be the preferred way for embedded document.
✨ Thank you for reading and I hope you find it helpful. I sincerely request for your feedback in the comment’s section. You can follow me on twitter @lifeClicks25.
Author Manish Prasad