How to Connect Node.js with MongoDB?
Short answer: install mongoose (or the official mongodb driver), keep your connection string in an environment variable, and connect once when the app starts. Reuse that single connection for every request.
Step 1: Install and get a connection string
npm install mongoose
Use a local server (mongodb://127.0.0.1:27017/myapp) or create a free cluster on MongoDB Atlas and copy its mongodb+srv://... string. New to the database? Read what MongoDB is.
Step 2: Store the string in .env
MONGODB_URI=mongodb+srv://USER:PASSWORD@cluster0.example.mongodb.net/myapp
Never hard-code credentials or commit this file. Loading it is covered in environment variables and dotenv.
Step 3: Connect with Mongoose
import mongoose from 'mongoose';
async function connectDB() {
try {
await mongoose.connect(process.env.MONGODB_URI);
console.log('MongoDB connected');
} catch (err) {
console.error('MongoDB connection failed:', err.message);
process.exit(1);
}
}
await connectDB();
Recent Mongoose versions need no extra options such as useNewUrlParser.
Step 4: Define a model and use it
const userSchema = new mongoose.Schema(
{ name: { type: String, required: true }, email: { type: String, unique: true } },
{ timestamps: true }
);
const User = mongoose.model('User', userSchema);
await User.create({ name: 'Sara', email: 'sara@example.com' });
const users = await User.find({ name: 'Sara' });
More operations are in MongoDB CRUD.
Using the official driver instead
import { MongoClient } from 'mongodb';
const client = new MongoClient(process.env.MONGODB_URI);
await client.connect();
const users = client.db('myapp').collection('users');
await users.insertOne({ name: 'Ali' });
| Mongoose | Native driver | |
|---|---|---|
| Schemas and validation | Built in | You write it |
| Learning curve | Easy | Close to MongoDB shell syntax |
| Best for | Most apps with structured data | Flexible or performance-critical code |
Reuse the connection
Open one connection per process, not one per request. In serverless or hot-reloading setups (such as Next.js), cache it on globalThis so each reload does not open a new one:
let cached = globalThis._mongoose;
if (!cached) cached = globalThis._mongoose = { conn: null, promise: null };
export async function connectMongo() {
if (cached.conn) return cached.conn;
cached.promise ??= mongoose.connect(process.env.MONGODB_URI);
cached.conn = await cached.promise;
return cached.conn;
}
Common errors and fixes
| Error | Likely cause |
|---|---|
| Server selection timed out | Your IP is not in the Atlas Network Access list, a firewall or VPN blocks it, or the host is wrong |
| Authentication failed | Wrong username or password; special characters in the password must be URL-encoded |
| ECONNREFUSED 127.0.0.1:27017 | The local MongoDB server is not running |
| URI must include hostname | The environment variable is undefined or malformed |
| Buffering timed out | You used a model before the connection finished |
Handle events and shutdown
mongoose.connection.on('error', (e) => console.error('DB error', e));
mongoose.connection.on('disconnected', () => console.warn('DB disconnected'));
process.on('SIGINT', async () => {
await mongoose.connection.close();
process.exit(0);
});
Best practices
- Use a database user with only the permissions the app needs.
- Restrict Atlas network access to known IPs where possible.
- Add indexes for fields you query; see indexing best practices.
- Keep the connection code in one module and import it where needed.
Frequently asked questions
Why does my connection to MongoDB Atlas time out?
The most common cause is that your IP address is not on the Atlas network access list. Also check the username and password, special characters that need URL encoding, and that your network allows outbound connections.
Should I connect to MongoDB on every request?
No. Open one connection when the app starts and reuse it. The driver manages a connection pool, so opening new connections per request wastes time and can exhaust the server limit.
Next steps
Expose the data through an API with Express.
