As you build more powerful Express apps, connecting to a database becomes essential. In this blog, we’ll walk through how to:
- Connect an Express app to MongoDB using Mongoose
- Secure your credentials using
.env
- Prevent sensitive files from being tracked with
.gitignore
Let’s get started.
Step 1: Install Required Packages
In your project directory, install:
npm install mongoose dotenv
-
mongoose
: ODM (Object Data Modeling) library for MongoDB -
dotenv
: Loads environment variables from.env
files
Step 2: Create .env
File
In the root of your project, create a .env
file:
touch .env
Add your MongoDB connection string:
MONGO_URI=mongodb+srv://<username>:<password>@cluster.mongodb.net/myDatabase
PORT=5000
Never share this file publicly.
Step 3: Setup .gitignore
To ensure .env
and other sensitive files aren’t committed to Git, create a .gitignore
file:
touch .gitignore
Add this to .gitignore
:
node_modules/
.env
Now Git will ignore node_modules
(which can be reinstalled) and .env
(which is sensitive).
Step 4: Create MongoDB Config
Create a file at src/config/db.js
:
const mongoose = require('mongoose');
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI);
console.log('MongoDB connected successfully');
} catch (error) {
console.error('MongoDB connection failed:', error.message);
process.exit(1);
}
};
module.exports = connectDB;
Step 5: Use dotenv
and Connect DB
Update your server.js
or app.js
:
// server.js
const dotenv = require('dotenv');
dotenv.config(); // Load .env before anything else
const express = require('express');
const connectDB = require('./src/config/db');
const app = express();
// Connect to MongoDB
connectDB();
// Middleware
app.use(express.json());
// Routes
app.get('/', (req, res) => {
res.send('Server running with MongoDB');
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Final Folder Snapshot
my-express-app/
├── node_modules/
├── src/
│ └── config/
│ └── db.js
├── .env
├── .gitignore
├── package.json
└── server.js
Step 6: Run Your App
Start the server:
node server.js
If successful, you’ll see:
MongoDB connected successfully
Server is running on http://localhost:5000
Bonus Tip: Use Environment Variables in Production
When you deploy (e.g., to Render or Vercel), add your MONGO_URI
and PORT
values to their dashboard under Environment Variables — no need to upload .env
.
Summary
- Use
mongoose
to connect MongoDB with Express - Use
.env
to store private credentials safely - Use
.gitignore
to prevent committing sensitive files - Never share
.env
ornode_modules
in Git
You now have a secure and scalable MongoDB connection in your Express app.