Mongoose subdocuments vs nested schema

2.3K    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

Interviews

Parent Categories