Mongoose BasicsIntermediate
1Question 1 of 1
javascriptWhat are Mongoose Schemas, Virtuals, and Middleware in Node.js applications?
Explanation & Concept
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js that provides schema validation, type casting, query building, and business logic hooks.
• Schema: Defines shape, default values, and validations. • Virtuals: Computed document properties that are not stored in MongoDB. • Middleware (Hooks): Pre/post functions executed during document lifecycle events (like `save`, `validate`, `remove`).
Code Example
javascript
import mongoose from "mongoose";
import bcrypt from "bcrypt";
const UserSchema = new mongoose.Schema({
email: { type: String, required: true, unique: true, lowercase: true },
password: { type: String, required: true, minlength: 8 }
});
// Pre-save middleware to hash passwords automatically
UserSchema.pre("save", async function () {
if (this.isModified("password")) {
this.password = await bcrypt.hash(this.password, 12);
}
});
export const User = mongoose.model("User", UserSchema);How It Works & Key Takeaways
The `pre('save')` hook ensures password hashing happens automatically right before MongoDB storage, keeping security logic centralized within the model definition.
Mock Test · 1 Questions · Optional
Ready for Query Optimization?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions