Beginner LevelMongoDB & Mongoose
How do Mongoose Schemas and Models enforce structure on MongoDB collections?
❓ Interview Prompt: Explain Mongoose ODM architecture, defining Schemas, compiling Models, connecting via mongoose.connect(), and connection pooling.
Mongoose is an Object Data Modeling (ODM) library for Node.js. It provides a straight-forward, schema-based solution to model application data:
•
Schema: Defines document structure, default values, validators, and hooks.
•
Model: Constructor compiled from a Schema that interfaces directly with MongoDB collections for querying and CRUD operations.
Code Implementation Example
typescript
import mongoose, { Schema, model } from 'mongoose';
interface IProduct {
title: string;
price: number;
}
const productSchema = new Schema<IProduct>({
title: { type: String, required: true },
price: { type: Number, required: true, min: 0 }
});
export const ProductModel = model<IProduct>('Product', productSchema);
// Connect to MongoDB instance
mongoose.connect('mongodb://127.0.0.1:27017/shopdb');💡Defining a strongly-typed Mongoose Schema and compiling a Model.
🎯 Interview Key Takeaway
Mongoose Schemas validate document structure before writing to MongoDB, while Models provide the query API.
#Mongoose#Schema#Model#ODM#Beginner
Back to all MongoDB & Mongoose Questions→