Table of contents
Introduction
Hello there. It's good to have you here. This is a continuation of the "Building Blog API" tutorial walkthrough. In case you missed the first article, check it out here. In this article, we will be connecting our application to the database. For this project, we will be using MongoDB Database. So let's dive right in.
MongoDB Atlas Setup.
In this section, I will be talking about how to create a cluster in MongoDB. MongoDB Atlas Cluster is a NoSQL Database-as-a-Service offering in the public cloud. If you are a new user, go ahead and create a free account here. If you are an existing user, simply sign in here. When you are done, you should see a page similar to the one below.
You can now go ahead and create a project.
The entire process is quite straightforward. Follow the prompts as they come. Here is a full tutorial on how to go about the rest of the process.
Connecting To MongoDB.
Since we are going to use MongoDB as the database, we should use the popular ORM called Mongoose. We are going to install it as a package. Also, assign a variable to the connection string and
Now create a folder and name it config and create a file inside the config folder and name it dbConnection.js and copy and paste the code below into it.
/config/dbConnection.js
const mongoose = require('mongoose')
require('dotenv').config()
function DbConnection(){
mongoose.connect(process.env.MONGODB_URL)
mongoose.connection.on('connected', ()=>{
console.log('Connection to MongoDB is successful')
})
mongoose.connection.on('error', (err)=>{
console.log('Unable to Connect to MongoDB');
console.log(err)
})
}
module.exports = {DbConnection}
The above code imports mongoose package and the dotenv package. Inside the DbConnection function, mongoose tries to connect to the MongoDB Connection String. If it is successful, it should connect and log a success string to the console. If it isn't successful, it should log a string telling us that.
The dbConnection.js file is then exported and we can import it into the index.js file. Here is an illustration.
/index.js
const { DbConnection } = require("./config/dbConnection");
DbConnection();
The code above imports the dbConnection.js file and the DbConnection function is called. Now open the terminal and enter node index.js
and hit enter. You should see that the server is running and the database is connected.
Conclusion.
Storing data is very important. In this article, we discussed how to set up MongoDB database and have the app running. Next is to implement user sign-in and sign-up functionalities.
Thanks for reading.