Understand Sub-documents & Nested documents in Mongoose
Mongoose is a popular schema-based tool for MongoDB. Explore the subtle difference between nested paths and subdocuments.
On this page 6 sections
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.
Quick answer
A nested path (others: { amount: Number }) is only a way of grouping fields on the parent schema. A subdocument (profile: new Schema({...})) is a child schema, so it gets its own _id, validators, middleware and virtuals. The price is that a single subdocument stays undefined until you assign it, and its defaults do not apply before that.
Sub-documents and Nested documents
Let us describe a schema of a person as below:
const mongoose = require('mongoose');
/**
* @class Person
*/
const personSchema = new mongoose.Schema({
name : {
type : String,
trim : true,
required : true,
},
// profile as sub document
profile : new mongoose.Schema({
city : String,
age : {
type : Number,
default : 0
},
}),
// others as nested document
others : {
amount : {
type : Number,
default : 0
},
email : {
type : String,
trim : true,
},
},
// array of objects; Mongoose turns each into a sub-document
friends : [
{ name: String }
],
// array of hobbies as sub document
hobbies : [
new mongoose.Schema({ name: 'string' })
]
});
module.exports = mongoose.model('Person', personSchema);In the above model:
-
profilefield is defined as a sub-document schema -
othersfield is defined as a nested document -
friendsis an array of plain objects; Mongoose converts it to a document array, so it behaves like sub-documents -
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.
const Model = mongoose.model('Person');
const doc = new Model();
console.log(doc.profile); // undefined
console.log(doc.others); // { amount: 0 }
doc.others.email = '[email protected]'; // doesn't throw error
// doc.profile.age = 35; // throw error
doc.profile = {};
console.log(doc.profile); // { age: 0, _id: 619e0c8be7d5e864f890e7ae }
doc.profile.age = 35; // doesn't throw error now
Now let us look at below code and understand the difference in arrays as well
const Model = mongoose.model('Person');
const doc = new Model();
const rec = {
name: 'Test User',
profile: {
city: 'Bengaluru',
age: 25
},
others: {
amount: 100,
email: '[email protected]'
},
friends: [{name: 'ABC'}, {name: 'XYZ'}],
hobbies: [{name: 'movies'}, {name: 'travel'}]
}
const newDoc = new Model(rec);
console.log(newDoc.profile);
console.log(newDoc.others);
console.log(newDoc.friends);
console.log(newDoc.hobbies);Output:
// profile
{ age: 25, _id: 619e4e79f828ad6a567d918f, city: 'Bengaluru' }Mongoose adds an _id field to subdocuments by default. It can be disabled by setting the _id option to false in sub-document definition
profile : new mongoose.Schema({
city : String,
age : {
type : Number,
default : 0
},
_id : false
}),No _id field in the single nested document
// others
{ amount: 100, email: '[email protected]' }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.
// friends
[
{ _id: 619e4e79f828ad6a567d9190, name: 'ABC' },
{ _id: 619e4e79f828ad6a567d9191, name: 'XYZ' }
]// hobbies
[
{ _id: 619e4e79f828ad6a567d9192, name: 'movies' },
{ _id: 619e4e79f828ad6a567d9193, name: 'travel' }
]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
// friends; no _id
[ { name: 'ABC' }, { name: 'XYZ' } ]
// hobbies; _id still added
[
{ _id: 619e51a3a341db6aec55c259, name: 'movies' },
{ _id: 619e51a3a341db6aec55c25a, name: 'travel' }
]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-document 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.
Two more differences worth knowing. In Mongoose 5, doc.set() merges when you call it on a nested path but overwrites when you call it on a subdocument. And subdocuments are never saved on their own; they are written when the parent is saved. If the undefined default bothers you, give the subdocument path default: () => ({}) so its own defaults apply.
The same question comes up one level higher: embed at all, or reference? Embed small, bounded data that is always read with its parent (an address, a profile). Reference lists that grow without limit or get queried on their own, and use populate to join them.
Conclusion
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.
Frequently Asked Questions
Why is my Mongoose subdocument undefined?
Single subdocument paths have no value until you set one, so their defaults never run. Assign {} or give the path default: () => ({}).
How do I stop Mongoose adding _id to subdocuments?
Pass _id: false in the child schema. For document arrays you can also call mongoose.Schema.Types.DocumentArray.set('_id', false), though array fields defined with an explicit sub-schema, like hobbies above, still get one.
Do nested paths support validators and hooks? Validators on a nested path as a whole are unreliable, because it is not a full path. Use a sub-document schema if you need validation, middleware or virtuals on that group of fields.
Related reading
- Mongoose Schema Validation: Best Practices and Anti-Patterns. Covers validators, including the nested-object caveat.
- Mongoose Population Deep Dive. For when embedding stops making sense.
- Avoiding Common Mongoose Schema Design Anti-Patterns. More on shaping schemas.
✨ 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 @manisuec.