We’ll cover how to connect your Node.js application to a remote MongoDB server using a username and password. This is crucial for securing your database and ensuring that only authorized users can access it.
Introduction
Connecting to a remote MongoDB server with authentication involves setting up your MongoDB instance to require authentication and then using the correct connection string in your Node.js application. We’ll walk through the steps to achieve this securely.
Step 1: Setting Up MongoDB User Authentication
1. Start MongoDB with Authentication
If MongoDB is not already running with authentication, start it with the --auth
flag:
mongod --auth --port 27017 --dbpath /var/lib/mongodb
2. Create an Admin User
First, connect to your MongoDB instance without authentication:
mongo --port 27017
Then, switch to the admin
database and create an admin user:
use admin;
db.createUser({
user: "admin",
pwd: "password123",
roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
});
Switch to your database (e.g., blogDB
) and create a user:
use blogDB;
db.createUser({
user: "blogUser",
pwd: "password123",
roles: [{ role: "readWrite", db: "blogDB" }]
});
Step 2: Connecting to MongoDB in Node.js
1. Install Mongoose
If you haven’t already, install Mongoose in your Node.js project:
npm install mongoose
2. Create a .env
File
Store your MongoDB connection URI and credentials in a .env
file for security:
MONGO_URI=mongodb://blogUser:password123@remote.mongodb.server:27017/blogDB
3. Setup Mongoose Connection
In your app.js
file or a dedicated database configuration file, setup Mongoose to connect to MongoDB:
require('dotenv').config();
const mongoose = require('mongoose');
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
});
console.log('MongoDB connected...');
} catch (err) {
console.error(err.message);
process.exit(1);
}
};
module.exports = connectDB;
In your main application file (app.js
):
const express = require('express');
const connectDB = require('./config/db');
const app = express();
// Connect to Database
connectDB();
// Define Routes
app.get('/', (req, res) => res.send('API Running'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
Step 3: Secure Your Application
1. Environment Variables
Make sure to add your .env
file to your .gitignore
to prevent sensitive information from being exposed:
# .gitignore
.env
2. Using Environment Variables in Deployment
When deploying your application, ensure that the environment variables are set up correctly on your hosting platform (e.g., Heroku, AWS).