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 mongoose
const 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.