Web Developer(Intern) @ Wikiance
This blog will teach you how to connect your Node.js application to the MongoDB Atlas. Well there are a couple of ways you can use mongodb. You can either install mongodb into your local machine or you can use use the cloud database which is the MongoDB Atlas.
Your computer must have enough RAM to support the application. I would suggest using Atlas for the beginners.So lets get started!
Go to the link https://www.mongodb.com/cloud/atlas and click on start free.
You will see something like this,
mongodb+srv://<username>:<password>@node-api-shop.5wrjk.mongodb.net/<dbname>?retryWrites=true&w=majority
The first step is to install the mongoose framework,
$npm install mongoose
Import the mongoose package into your code,
const mongoose = require('mongoose'); //imports mongoose package
const url = 'mongodb+srv://JohnDoe:1234@node-api-shop.5wrjk.mongodb.net/<dbname>?retryWrites=true&w=majority';
Connect to the database,
mongoose.connect(uri, { useUnifiedTopology: true }, { useNewUrlParser: true });
unifiedTopology and useNewUrlParser are the configuration properties added to prevent deprecation warnings
And with that you are connected to the database.
To verify that add a callback function to the connect() method
mongoose.connect(uri,
{ useUnifiedTopology: true },
{ useNewUrlParser: true },
function() { console.log('connected...') }
);
So, when you are connected successfully, it logs as connected!
With that you have now linked your application to the database :)
3 Comments
"When I read your blogpost, I feel so much at peace. This is an excellent piece of writing Minaz. Well done"
Same here...I feel he is good at writing