How to Connect Express to MongoDB: Simple Guide
To connect
Express to MongoDB, use the mongoose library by importing it, then call mongoose.connect() with your MongoDB URI before starting your Express server. This sets up a database connection that your Express app can use to read and write data.Syntax
Here is the basic syntax to connect Express to MongoDB using Mongoose:
import mongoose from 'mongoose': Imports the Mongoose library.mongoose.connect(uri, options): Connects to MongoDB using the connection stringuriand optional settings.app.listen(port): Starts the Express server after the database connection is successful.
javascript
import express from 'express' import mongoose from 'mongoose' const app = express() const uri = 'your_mongodb_connection_string' mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log('Connected to MongoDB') app.listen(3000, () => console.log('Server running on port 3000')) }) .catch(err => console.error('MongoDB connection error:', err))
Output
Connected to MongoDB
Server running on port 3000
Example
This example shows a simple Express app connecting to MongoDB with Mongoose. It logs success or error messages and starts the server only after the database is connected.
javascript
import express from 'express' import mongoose from 'mongoose' const app = express() const mongoUri = 'mongodb://localhost:27017/mydatabase' mongoose.connect(mongoUri, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log('MongoDB connected successfully') app.get('/', (req, res) => { res.send('Hello from Express connected to MongoDB!') }) app.listen(3000, () => console.log('Server listening on port 3000')) }) .catch(error => { console.error('Error connecting to MongoDB:', error) })
Output
MongoDB connected successfully
Server listening on port 3000
Common Pitfalls
Common mistakes when connecting Express to MongoDB include:
- Not waiting for the database connection before starting the server, which can cause errors when handling requests.
- Using an incorrect or missing MongoDB URI.
- Not handling connection errors properly.
- Omitting important options like
useNewUrlParseranduseUnifiedTopologywhich help avoid deprecation warnings.
Always use then or async/await to ensure the connection is ready before your app starts.
javascript
/* Wrong way: Starting server without waiting for DB connection */ import express from 'express' import mongoose from 'mongoose' const app = express() const uri = 'mongodb://localhost:27017/testdb' mongoose.connect(uri) app.listen(3000, () => console.log('Server started')) // May start before DB connects /* Right way: Wait for connection before starting server */ mongoose.connect(uri) .then(() => { app.listen(3000, () => console.log('Server started after DB connected')) }) .catch(err => console.error('DB connection error:', err))
Output
Server started after DB connected
Quick Reference
Tips for connecting Express to MongoDB:
- Use
mongoose.connect()with your MongoDB URI. - Include options
{ useNewUrlParser: true, useUnifiedTopology: true }to avoid warnings. - Start your Express server only after the database connection succeeds.
- Handle connection errors with
catchortry/catch. - Use environment variables to store your MongoDB URI securely.
Key Takeaways
Use Mongoose's mongoose.connect() with your MongoDB URI to connect Express to MongoDB.
Always wait for the database connection to succeed before starting your Express server.
Include connection options like useNewUrlParser and useUnifiedTopology to avoid warnings.
Handle connection errors properly to prevent your app from crashing.
Store your MongoDB URI securely, preferably in environment variables.