In this post, I will tell you how you can connect to MongoDB Atlas, a cloud-based DB service, from your local Node.js / Express.js environment.
You can use Atlas for any project which needs to be deployed, whether for development purpose or production environment.
Let's get started!
Step 1: Register/Login and create your plan
Create your account at Atlas and register yourself to their service. It's free of cost. If you already have an account, go ahead. If you logging in for the first time, you will need to choose a plan for your account. There are 3 types to choose from, for testing and learning purpose, "FREE PLAN" will suit your needs perfectly. After doing all basic registration and setup, it's time to create a Cluster.
Step 2: Create your Cluster
After Registration/Login and choosing your plan, let's get our Cluster setup done.
If you have no created clusters, you will see the below page on your dashboard.
Upon clicking "Build a cluster", you will be given with the following options:
Here, on this page, you need to select Cloud Provider, and your Region. Upon selecting those, you can leave all other settings to their default and can go ahead. If you want to change the name of your Cluster, you have to do it in this step only. Name cannot be changed once the cluster is created.
Completing all the above steps is what you need to create a Cluster. Now, MongoDB will configure and create your cluster and this process will take about 5-10 minutes (pretty long tbh). Come back to the same page once all is finished.
We will now look at how to create and configure database collections and integrate it with our express server
Step 3: Add User and whitelist IP address
Till this step, we have successfully created our Cluster. Now, its time to add Database User and IP address of your current machine.
- Add database user Go to Database access under SECURITY and click on "Add New Database User". Fill out the username and password, leaving all settings to default and make sure you remember your credentials. We will need it later on to create a connection string (URI) of our DB.
- Whitelist your IP address Now, the next step is to Whitelist your IP address so it can recognize your machine for regular access. To whitelist your IP address, go to SECURITY > Network Access and click on "Add IP Address". Upon clicking that, you will be given with the following page. Click on Allow access from anywhere which sets it to global access. Don't worry, its not any danger.
Now, we've all set up done to use it to our Node.js server. It's time for some code.
Step 4: Connect to your database
In this step, we will connect our server to the database. To do this, go to the main page of your cluster and click on "Connect" which will give you a modal like this:
Select "Connect your application". On clicking, you have to select "Node.js" in the next page and save the connection string provided by Atlas somewhere for further use.
Now, its time to create our database connection using mongoose. Install mongoose in your project by npm install mongoose. Copy-paste the following code to db.js.
//db.js
const mongoose = require('mongoose')
const url = `mongodb+srv://sample_user:<password>@my-sample-cluster-b3ugy.mongodb.net/<dbname>?retryWrites=true&w=majority`;
const connectionParams={
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
}
mongoose.connect(url,connectionParams)
.then( () => {
console.log('Connected to database ')
})
.catch( (err) => {
console.error(`Error connecting to the database. \n${err}`);
})
Replace "password" with your user password and also the "dbname" with the name you'd like to have for your database. Run the following code by typing node db.js and you will see Connected to the database in your console. You can take this to the next step by configuring your DB model by creating a "Collection" with various fields and connecting it with the express server. I leave it up to you to use according to your need. This was the basic setup needed to get Atlas up and running.
Conclusion
Hooray, this way we have successfully connected to Atlas using Node.js. If you have any doubts, feel free contact me and I will try to resolve it on a personal basis.
Thank you.
Top comments (12)
const mongoose = require("mongoose");
const url = "mongodb+srv://userName:@cluster0.xesyn.mongodb.net/DBname?retryWrites=true&w=majority";
mongoose.connect(url, (err) => {
if (err) throw err;
console.log("Database created!");
});
I Connect in this way
you explained in details thank you so much
Is it a good practice to provide mongo admin password in app.js ? as if i push the code to git it might give warning . Btw i am new to node js. if not then what is best way to provide the password of admin in mongo url ?
you can pass the credentials via environment variables and make sure you don't push that to git. something like is used in production
added this just for demo purpose ;)
thanks a lot for the reply yes i tried using above step only
Thanks this helped.
Hi, my coding friend!
I believe replacing
const url =
...
withconst url = process.env.ATLAS_URI
would be a more secured approach.
Yes, definitely my coding friend.
I've added , for demo purpose.
Thanks a lot that helped 😄
const express = require("express");
const app = express();
const { MongoClient } = require("mongodb");
const PORT = 4000;
let db;
let connectionString = mongodb+srv://suyogkubde02:9881815220@cluster0.i2ofrpx.mongod.../?retryWrites=true&w=majority;
// app.use(express.json());
MongoClient.connect(
mongodb+srv://suyogkubde
:****@cluster0.i2ofrpx.mongodb.net/?retryWrites=true&w=majority,
{ useNewUrlParser: true },
(error, client) => {
console.log("error :", error);
console.log("client : ", client);
if (error) {
return console.log("Connection failed for some reason");
}
console.log("Connection established - All well");
db = client.db("crud");
app.listen(PORT, function () {
console.log("Server is running on Port: " + PORT);
});
}
);
For now I have just removed the password.
When I do node server.js it doesn't give any error or any output it just keep on loading even the execution don't end.
Ah... thanks. This was simple enought for me.
thanks yar tune meri problem solve kr di!
i got this error
MongoParseError: option usecreateindex is not supported
later i came to know usecreateindex is know not supported in mongoos 6 so no need to add it