Mongoose subdocuments vs nested schema

2.4K    Asked by arun_3288 in Big Data Hadoop , Asked on Jun 24, 2021

 I'm curious as to the pros and cons of using subdocuments vs a deeper layer in my main schema:

var subDoc = new Schema({
  name: String
});
var mainDoc = new Schema({
  names: [subDoc]
});

or

var mainDoc = new Schema({
  names: [{
    name: String
 }]
});

I'm currently using subdocs everywhere but I am wondering primarily about performance or querying issues I might encounter. What is mongoose nested schema?

Answered by Camellia Kleiber

 In Mongoose, the subdocuments are considered to be those documents that are embedded inside the other documents. The instance that you have shown, both are implying the same thing that is embedded documents. There are no pros and cons regarding the subdocuments and nested documents. The nested schema is very similar to the top-level schemas as this nested schema comprises middleware, custom-validation-logic, and virtuals. The subdocuments are incapable of saving individual documents. Instead, they are saved when their top-level parent document is saved.

Mongoose helps you create nested schemas when you nest an object in another object.



Your Answer

Answer (1)

In Mongoose, both subdocuments and nested schemas are used to structure documents in a more complex way. They allow you to embed documents within other documents. Here's a detailed comparison to help you understand the differences and use cases for each:

Subdocuments

Subdocuments are documents embedded within other documents. They are used when you want to represent a hierarchy of documents, but they are not treated as standalone schemas. They are defined directly within the parent schema.

Example

  const mongoose = require('mongoose');const Schema = mongoose.Schema;// Define a subdocument schemaconst addressSchema = new Schema({  street: String,  city: String,  state: String,  zip: String});// Define the parent schemaconst userSchema = new Schema({  name: String,  address: addressSchema // Embedding the subdocument schema directly});

  const User = mongoose.model('User', userSchema);// Creating a document with a subdocumentconst newUser = new User({  name: 'Pawan',  address: {    street: '123 Main St',    city: 'Anytown',    state: 'CA',    zip: '12345'  }});newUser.save()  .then(user => console.log(user))  .catch(err => console.log(err));

Nested Schema

Nested schemas are similar to subdocuments but are defined as standalone schemas. They can be reused in multiple parent schemas, making them more modular and maintainable.

Example

  const mongoose = require('mongoose');const Schema = mongoose.Schema;// Define a nested schemaconst addressSchema = new Schema({  street: String,  city: String,  state: String,  zip: String});// Define the parent schemaconst userSchema = new Schema({  name: String,  address: { type: addressSchema, required: true } // Using the nested schema});const User = mongoose.model('User', userSchema);// Creating a document with a nested schemaconst newUser = new User({  name: 'Pawan',  address: {    street: '123 Main St',    city: 'Anytown',    state: 'CA',    zip: '12345'  }});newUser.save()  .then(user => console.log(user))  .catch(err => console.log(err));Differences and Use CasesDefinition:Subdocuments: Defined directly within the parent schema. They are tightly coupled with the parent schema.Nested Schema: Defined as separate, reusable schemas that can be referenced in multiple parent schemas.Reusability:Subdocuments: Not easily reusable since they are defined within the parent schema.Nested Schema: Easily reusable in multiple schemas, promoting modularity and reducing code duplication.Validation and Methods:Subdocuments: Can have their own validation and methods but are limited to the scope of the parent schema.Nested Schema: Have full capabilities of a schema, including validation, methods, and middleware.Complexity:

Subdocuments: Simpler to define and use within a single schema.

Nested Schema: More complex to set up but provide greater flexibility and maintainability for larger projects.

When to Use What?

Subdocuments: Use subdocuments when the embedded document is specific to a single parent schema and does not need to be reused elsewhere.

Nested Schema: Use nested schemas when the embedded document structure is more complex, requires its own methods and validation, or needs to be reused in multiple schemas.

Choosing between subdocuments and nested schemas depends on your application's complexity and the need for modularity and reusability. For smaller projects or when embedding simple data structures, subdocuments are often sufficient. For larger projects with complex data structures, nested schemas offer better organization and maintainability.

1 Week

Interviews

Parent Categories