Node.js10 min read

MongoDB with Mongoose in Node.js

Connect Node.js to MongoDB using Mongoose. Learn schemas, models, and CRUD operations.

Sarah Chen
December 19, 2025
0.0k0

MongoDB with Mongoose in Node.js

Mongoose is the most popular MongoDB library for Node.js. It adds schemas, validation, and more.

Setup

```bash npm install mongoose ```

Connect to MongoDB

```javascript const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myapp') .then(() => console.log('Connected to MongoDB')) .catch(err => console.error('Connection error:', err)); ```

Define a Schema

```javascript const userSchema = new mongoose.Schema({ name: { type: String, required: true, trim: true }, email: { type: String, required: true, unique: true, lowercase: true }, age: { type: Number, min: 0, max: 120 }, role: { type: String, enum: ['user', 'admin'], default: 'user' }, createdAt: { type: Date, default: Date.now } });

const User = mongoose.model('User', userSchema); ```

Create Documents

```javascript // Method 1: new + save const user = new User({ name: 'Alice', email: 'alice@example.com', age: 25 }); await user.save();

// Method 2: create const user2 = await User.create({ name: 'Bob', email: 'bob@example.com' }); ```

Read Documents

```javascript // Find all const users = await User.find();

// Find with conditions const admins = await User.find({ role: 'admin' });

// Find one const user = await User.findOne({ email: 'alice@example.com' });

// Find by ID const user = await User.findById('507f1f77bcf86cd799439011');

// Select specific fields const users = await User.find().select('name email');

// Sort const users = await User.find().sort({ createdAt: -1 });

// Limit const users = await User.find().limit(10);

// Pagination const page = 2; const limit = 10; const users = await User.find() .skip((page - 1) * limit) .limit(limit); ```

Update Documents

```javascript // Find and update const user = await User.findByIdAndUpdate( '507f1f77bcf86cd799439011', { name: 'Alice Smith' }, { new: true } // Return updated document );

// Update many await User.updateMany( { role: 'user' }, { $set: { verified: true } } ); ```

Delete Documents

```javascript // Delete one await User.findByIdAndDelete('507f1f77bcf86cd799439011');

// Delete many await User.deleteMany({ role: 'guest' }); ```

Schema Options

```javascript const postSchema = new mongoose.Schema({ title: String, content: String, author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' // Reference to User model }, tags: [String], // Array of strings metadata: { views: { type: Number, default: 0 }, likes: { type: Number, default: 0 } } }, { timestamps: true // Adds createdAt, updatedAt }); ```

Populate (Join)

```javascript // Get posts with author details const posts = await Post.find() .populate('author', 'name email');

// Result includes full author object // { title: '...', author: { name: 'Alice', email: '...' } } ```

Instance Methods

```javascript userSchema.methods.getPublicProfile = function() { return { id: this._id, name: this.name, email: this.email }; };

const user = await User.findById(id); const profile = user.getPublicProfile(); ```

Static Methods

```javascript userSchema.statics.findByEmail = function(email) { return this.findOne({ email }); };

const user = await User.findByEmail('alice@example.com'); ```

Middleware (Hooks)

```javascript // Before saving userSchema.pre('save', async function(next) { if (this.isModified('password')) { this.password = await bcrypt.hash(this.password, 10); } next(); });

// After saving userSchema.post('save', function(doc) { console.log('User saved:', doc.email); }); ```

Express Integration

```javascript // models/User.js const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true } });

module.exports = mongoose.model('User', userSchema);

// routes/users.js const User = require('../models/User');

router.get('/', async (req, res) => { const users = await User.find(); res.json(users); });

router.post('/', async (req, res) => { const user = await User.create(req.body); res.status(201).json(user); }); ```

Key Takeaway

Mongoose provides schemas for MongoDB. Define schemas with types and validation, create models, then use find/create/update/delete. Use populate for joins, middleware for hooks. It's the standard way to work with MongoDB in Node.js.

#Node.js#MongoDB#Mongoose#Database#Intermediate