Beginner LevelMongoDB & Mongoose
How do Mongoose Subdocuments and nested array schemas work?
❓ Interview Prompt: Explain Mongoose Subdocuments, embedded schema arrays, subdocument _id generation, and parent document persistence.
Subdocuments are documents embedded inside parent documents, defined using nested Mongoose schemas:
Characteristics:
•
Each subdocument automatically gets its own '_id'.
•
Subdocuments have validation rules and pre/post save hooks.
•
Parent document 'save()' persists all nested subdocuments atomically.
Code Implementation Example
typescript
import { Schema, model } from 'mongoose';
const itemSchema = new Schema({ title: String, price: Number });
const cartSchema = new Schema({
userId: String,
items: [itemSchema] // Embedded subdocument array
});
export const CartModel = model('Cart', cartSchema);💡Defining embedded subdocument arrays within a parent Mongoose schema.
🎯 Interview Key Takeaway
Subdocuments allow nesting schemas inside arrays while maintaining distinct validation rules and subdocument _ids.
#Subdocuments#Embedded Schemas#Mongoose#Beginner
Back to all MongoDB & Mongoose Questions→