I am a beginner, Can anyone tell me why we have to need to import the whole schema into a new schema Object as an array? what's that Purpose?
pages: [nestedSchema]
E.g if I have
role_name: {
type: String,
},
pages: {
type: [nestedSchema],
},
});
const nestedSchema = new mongoose.Schema({
page_id: {
type: mongoose.Schema.Types.ObjectId,
ref: "page",
required: true,
},
view: {
type: Boolean,
default: true,
},
add: {
type: Boolean,
default: false,
},
edit: {
type: Boolean,
default: false,
},
delete: {
type: Boolean,
default: false,
},
});
I want to know why we need it To Place the Whole Schema into another as an Array. Because another way is available (refs&Populate), Is it Right to do it in this Way Or Not? If Yes then How do we get page[] array whole data just like (refs&populate) usage?
CodePudding user response:
By using [ nestedSchema ]
, you're configuring subdocuments. These are saved as part of the main/parent document, but by creating a nested schema, you get all the benefits that Mongoose provides for documents in general, like validation, middleware, etc.
With population, you can create references between two distinct models, a bit like foreign keys or joins in SQL.
It's not a question of "which one is better", both have their own merits.
As an example, say you have a User
model, and that you want to store the address where the user lives.
You can use a nested schema for this:
const addressSchema = new mongoose.Schema({
...
});
const userSchema = new mongoose.Schema({
firstName : String,
lastName : String,
address : addressSchema
});
This will save the address along with rest of the user data.
But what if want to allow multiple users of the same family to be added to your database? With the above setup, using subdocuments, if there's a change in the family's address, you have to change all the user documents for that family to update the address, because each user document contains the full address document.
With population, the User
model refers to a separate Address
model:
const addressSchema = new mongoose.Schema({
...
});
const userSchema = new mongoose.Schema({
firstName : String,
lastName : String,
address : { type: mongoose.Schema.Types.ObjectId, ref: 'Address' }
});
Then, if there's an address change, you only have to modify one Address
document and it will be automatically updated for each user that lives on that address.