How to Use Mongoose with Express: Simple Integration Guide
To use
mongoose with express, first install both packages, then connect Mongoose to your MongoDB database using mongoose.connect(). Use Mongoose models to define data schemas and interact with the database inside your Express routes.Syntax
This is the basic pattern to use mongoose with express:
- Import packages: Bring in
expressandmongoose. - Connect to MongoDB: Use
mongoose.connect()with your database URL. - Define a schema and model: Create a Mongoose schema to shape your data and a model to interact with it.
- Use model in routes: Perform database operations inside Express route handlers.
javascript
import express from 'express'; import mongoose from 'mongoose'; const app = express(); app.use(express.json()); mongoose.connect('mongodb://localhost:27017/mydb') .then(() => console.log('Connected to MongoDB')) .catch(err => console.error('MongoDB connection error:', err)); const schema = new mongoose.Schema({ name: String }); const Model = mongoose.model('Model', schema); app.post('/items', async (req, res) => { const item = new Model(req.body); await item.save(); res.send(item); }); app.listen(3000, () => console.log('Server running on port 3000'));
Output
Connected to MongoDB
Server running on port 3000
Example
This example shows a simple Express server connected to MongoDB using Mongoose. It defines a Book model and a POST route to add new books to the database.
javascript
import express from 'express'; import mongoose from 'mongoose'; const app = express(); app.use(express.json()); mongoose.connect('mongodb://localhost:27017/library') .then(() => console.log('MongoDB connected')) .catch(err => console.error('Connection error:', err)); const bookSchema = new mongoose.Schema({ title: String, author: String, pages: Number }); const Book = mongoose.model('Book', bookSchema); app.post('/books', async (req, res) => { try { const book = new Book(req.body); await book.save(); res.status(201).send(book); } catch (error) { res.status(400).send({ error: error.message }); } }); app.listen(4000, () => console.log('Server listening on port 4000'));
Output
MongoDB connected
Server listening on port 4000
Common Pitfalls
Common mistakes when using Mongoose with Express include:
- Not calling
express.json()middleware, soreq.bodyis undefined. - Forgetting to handle asynchronous operations with
async/awaitor.then(), causing unhandled promises. - Not catching errors from Mongoose operations, leading to server crashes.
- Using incorrect MongoDB connection strings or not waiting for connection before starting the server.
javascript
/* Wrong: Missing express.json middleware */ import express from 'express'; import mongoose from 'mongoose'; const app = express(); mongoose.connect('mongodb://localhost:27017/testdb'); const User = mongoose.model('User', new mongoose.Schema({ name: String })); app.post('/users', async (req, res) => { // req.body will be undefined here const user = new User(req.body); await user.save(); res.send(user); }); app.listen(3000); /* Right: Add express.json middleware */ app.use(express.json());
Quick Reference
Tips for smooth Mongoose and Express integration:
- Always use
express.json()to parse JSON request bodies. - Use
async/awaitwith try/catch for database calls. - Define clear Mongoose schemas to validate data.
- Connect to MongoDB before starting the Express server.
- Close the database connection gracefully on app shutdown.
Key Takeaways
Connect Mongoose to MongoDB before starting your Express server.
Use Mongoose models inside Express routes to handle database operations.
Always include express.json() middleware to parse incoming JSON data.
Handle async database calls with async/await and try/catch blocks.
Define schemas to enforce data structure and validation.