What is Mongoose, and how does it act as an Object Data Modeling (ODM) library for MongoDB?
In : MCA Subject : Full Stack Web Development using MERNMongoose is a Node.js library that helps you manage data in MongoDB by providing a structured way to work with your database. Even though MongoDB doesn’t require a fixed structure, Mongoose lets you define schemas and models for your data, like specifying what fields an item should have and what types they should be (e.g., string, number).
This is called Object Data Modeling (ODM). With Mongoose, you can add validations (like making a field required), set default values, and use middleware (code that runs before or after saving data). It also makes it easier to perform operations like creating, reading, updating, and deleting data using simple JavaScript methods. Overall, Mongoose acts as a bridge between your Node.js app and MongoDB, making data handling more organized, reliable, and developer-friendly.
Example: Using Mongoose to Model a User
// 1. Import Mongoose
const mongoose = require('mongoose');
// 2. Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/myapp');
// 3. Define a Schema
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
age: {
type: Number,
min: 0,
max: 120
},
isActive: {
type: Boolean,
default: true
},
createdAt: {
type: Date,
default: Date.now
}
});
// 4. Create a Model
const User = mongoose.model('User', userSchema);
// 5. Use the Model (CRUD Example)
async function createUser() {
const user = new User({
name: "John Doe",
email: "john@example.com",
age: 30
});
try {
const savedUser = await user.save();
console.log(savedUser);
} catch (err) {
console.error(err);
}
}
createUser();