
How to Connect MongoDB with Your Node.js App in cPanel
How to Connect MongoDB with Your Node.js App in cPanel
Overview
Whether you’re using MongoDB Atlas (cloud-based) or a local MongoDB server, this guide will help you integrate it into your Node.js app hosted via cPanel.
Requirements
- Node.js App hosted in cPanel (via Application Manager)
- MongoDB Atlas account or access to MongoDB URI
mongoose
or MongoDB native driver installed
1. Install Mongoose in Your Node.js App
- Login to your cPanel
- Go to Setup Node.js App
- Open Terminal in the app root directory or use SSH
- Run the following command:
npm install mongoose
2. Get Your MongoDB URI
- For MongoDB Atlas:
mongodb+srv://username:password@cluster.mongodb.net/dbname?retryWrites=true&w=majority
- For local/hosted MongoDB:
mongodb://localhost:27017/mydatabase
3. Add Your MongoDB URI as an Environment Variable (Recommended)
- In cPanel, go to Setup Node.js App
- Click Edit on your application
- Scroll down to Environment Variables
- Add:
MONGODB_URI = your-mongodb-uri
- Click Save and then Restart the app
4. Update Your Node.js Code
In your main file (e.g. index.js
), use the following code to connect MongoDB:
const mongoose = require('mongoose');
const uri = process.env.MONGODB_URI;
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('MongoDB connected successfully'))
.catch(err => console.error('MongoDB connection error:', err));
Alternative: Use MongoDB Native Driver
const { MongoClient } = require('mongodb');
const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
console.log("Connected to MongoDB");
const db = client.db("your-database");
// perform actions on the collection
} finally {
await client.close();
}
}
run().catch(console.dir);
Tip: Never hardcode credentials. Always use environment variables for security and portability.
Troubleshooting
- Check cPanel Error Logs if your app fails to start
- Ensure your IP is whitelisted in MongoDB Atlas (under Network Access)
- Confirm
mongoose
ormongodb
is listed inpackage.json
Need Help?
Contact our Hiverift support team at dev@hiverift.com for MongoDB setup assistance with your Node.js app.