MongoDB Atlas is a Database-as-a-Service platform, and It’s most popular among MEAN/MEAN stack-powered web applications.
The mongo db Atlas has a free tier to use.
This blog will cover how to get started with mongo db atlas and how we can connect with express js backend.
Signup with MongoDB Atlas
You signup up with your email or by using your existing Gmail account to get started with Atlas.
After successfully signing up, you will be prompted to set up your project’s initiation.
Here select Javascript as the preferred language. And click the finish button to proceed.
Create a New Cluster
After finishing your project initiation process on the next page, you will see the configurations to create a new cluster
You can get started with the free MO tier, and give a name for your database cluster.
Allow Access
After successfully creating the cluster, you need to set up the access configuration.
Select Username and Password as authentication connection, and create a user by providing a username and password. (You can change this at any given time based on your requirement)
After that, you need to provide an IP address to access the cluster.
For demonstration purposes, we are going to use 0.0.0.0/0 as the IP address. This will allow you to access the cluster from anywhere in the world (whitelist entry).
Get the Connection URI String
Click the database in the side navigation and select connect button to get the connection string.
Select drivers as the preferred connection method from the window popup.
Select node.js as a driver and the latest version in the next step.
And then you will able to see the connection string to connect the newly created cluster with the express JS/ node JS application. Copy this string by clicking copy icon.
Connect the Cluster with the Express js app
We are going to use dotenv as well as mongoose npm packages.
Dotenv enables you to get process sensitive information without explicitly showing the credentials through the app.
Mongoose is a MongoDB object modelling tool for express js.
(You can see a comprehensive list of npm packages for express js from this link.)
Install these packages via your project terminal.
npm install dotenv mongoose
Create .env file on your root folder and paste the string you copied from the Mongo db atlas.
You need to manually enter your password in the URI string.
Replace <password>
tag with your password value. In my case, my password will be admin_123.
PORT=3000
MONGODB_URI=mongodb+srv://admin:admin_123@democluster.ww9qhi9.mongodb.net/?retryWrites=true&w=majority
By using the Mongoose package you can easily connect your atas cluster with express js like this in the server.js file.
require('dotenv').config(); // Load environment variables from .env file
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const port = process.env.PORT || 3000;
// Mongoose database connection
mongoose
.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("DB Connected"))
.catch(error => console.error(`DB connection error: ${error.message}`));
mongoose.connection.on("error", err => {
console.log(`DB connection error: ${err.message}`);
});
// Define your routes and middleware here
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
If all the above steps work you will see the “DB Connected” message in the project terminal.
Check the full code from this GitHub repository.
Happy learning/coding 😎