MongoDB & Mongoose ODM
MongoDB is a NoSQL database that stores data as flexible JSON-like documents. Mongoose is the most popular ODM (Object Data Mapper) for Node.js, adding schemas, validation, and model methods on top of MongoDB's driver.
1 Connecting & Defining a Schema
JavaScript — Mongoose Setup & Schema
const mongoose = require('mongoose');
// Connect to MongoDB
async function connectDB() {
try {
await mongoose.connect(process.env.MONGODB_URI);
console.log('MongoDB connected successfully');
} catch (err) {
console.error('Connection failed:', err.message);
process.exit(1);
}
}
connectDB();
// Define a Schema
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Name is required'],
trim: true,
minlength: 2
},
email: {
type: String,
required: true,
unique: true,
lowercase: true,
match: [/^S+@S+.S+$/, 'Invalid email format']
},
role: {
type: String,
enum: ['user', 'admin', 'editor'],
default: 'user'
},
createdAt: { type: Date, default: Date.now }
});
// Add instance methods
userSchema.methods.toPublicJSON = function() {
const { _id, name, email, role } = this;
return { id: _id, name, email, role };
};
const User = mongoose.model('User', userSchema);
module.exports = User;
2 CRUD with Mongoose
JavaScript — Mongoose CRUD
// CREATE
const user = await User.create({ name: 'Balaji', email: 'b@example.com' });
// READ — find all, with pagination
const users = await User.find({ role: 'user' })
.select('name email -_id')
.sort({ name: 1 })
.skip(0).limit(10);
// READ — find one by id
const found = await User.findById(req.params.id);
if (!found) throw new Error('User not found');
// UPDATE — findByIdAndUpdate returns the updated doc
const updated = await User.findByIdAndUpdate(
req.params.id,
{ name: 'Updated Name' },
{ new: true, runValidators: true }
);
// DELETE
await User.findByIdAndDelete(req.params.id);
3 Code Challenge
Challenge: Define a Mongoose schema for a
Product with fields: name, price (Number, min 0), category, and inStock (Boolean). Write a query that finds all in-stock products sorted by price.