How to connect MongoDB to Node.js
In the previous blog we saw how to create a simple server with Node.js and Express.js , now we will continue with connecting our MongoDB.
Before we start creating our backend, let’s setup our database. We will be using MongoDB Atlas, which is a free service (at the basic tier) allowing us to host our database online. Follow these steps to setup your database:
* Go to the website and create an account
- Click Build a cluster
we will free cluster for this course because it’s enough for our needs.
- you can select ant cloud provider you like, for me I will select Amazon Web Services as cloud provider
- Leave everything else as defaults
- Wait for the cluster to be created (7–10 min)
- Click the
Connectbutton on the newly created cluster
Add a different IP addressand enter
0.0.0.0/0to allow connections from any IP
- Next create a new user
- Give them whatever username you like I.E.
Autogenerate Secure Passwordbutton and save the password for later DO NOT COMMIT THE PASSWORD
- Click chose a connection method
Connect Your Application
- Copy and paste the connection string
- replace the
<username>with the username we just created
- replace the
<password>with the auto-generated password
- now that we have this connection string we want to save it somewhere it won’t be committed
Let’s connect our database to MongoDB Atlas. Recall the string you saw at the end of the Atlas setup
- Create a new directory named ‘config’
- Make a new file within that directory called
- Add the following code to
- Make sure to replace
dbpasswordwith the password you created during the Atlas setup.
Now is time to go back to our server file that we created in last blog so we can make the connection with our DB
- require mongoose
keys.jsfile that has our DB link to MongoDB Atlas
- On the next line, we will connect to MongoDB using Mongoose:
PS( calling MongoDB gives you back a promise so you can use
then or async )
As long as you have followed the above steps successfully and entered the correct username and password, you should see your success message in the console. That’s it! Mongoose is up and running.
Next blog we will create a model and save our info in Database we just created