Node.js Masterclass
High-Performance Backends01.Home02.Introduction03.Environment Setup04.Modules & Exports05.File System (fs)06.Path & OS Modules07.Buffer & Streams08.Events & EventEmitter09.HTTP Module10.NPM & Package.json11.Express.js Fundamentals12.Express Routing13.Express Middleware14.RESTful API Development15.Asynchronous Programming16.Error Handling17.Database with Mongoose18.Authentication with JWT19.Environment Variables20.Testing with Jest21.Deployment & PM2
Database with Mongoose
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a straight-forward, schema-based solution to model your application data.
1. Installation & Connection
npm install mongooseconst mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test_db')
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.error('Could not connect...', err));2. Defining a Schema
Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, unique: true },
age: Number,
createdAt: { type: Date, default: Date.now }
});
const User = mongoose.model('User', userSchema);3. CRUD Operations
Mongoose makes interacting with the database very simple using model methods.
// Create
const newUser = await User.create({ name: 'John Doe', email: 'john@example.com' });
// Read
const users = await User.find({ age: { $gte: 18 } });
// Update
await User.findByIdAndUpdate(id, { name: 'Updated Name' });
// Delete
await User.findByIdAndDelete(id);Advantage: Mongoose adds built-in validation, type casting, and middleware (hooks) that aren't available in the native MongoDB driver.