Node.js API + MongoDB CRUD Operations | Part 02

Nimasha Madhushani
LinkIT
Published in
5 min readJan 6, 2023

--

Artwork by Author

This is Part 02 of the series of Node.js API + MongoDB CRUD Operations. If you didn’t read Part 01, you are not late here is the link, and spent little 4 minutes on it. [Link to Part 01].

Now you have initiated the node project. Then run it on an integrated terminal by using npm start. Now, the time is to do other imports and configurations to connect the database to our application.

Therefore, we have to import the body-parser package into the index.js(server) file. This package is used to convert the request body into a given format then it will be inside the middleware. We can configure middleware using use() method. Then, whatever the request comes to the application the body will be converted to an JSON object.

const bodyParser = require("body-parser");
app.use(bodyParser.json());

Hereafter this implementation, your index.jsfile will be as below,

const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());

app.listen(3000, () => console.log("Server is started on 3000"));

Yeah, It’s time to set up the database in MongoDB.😎

Here, we use online MongoDB. You can go to MongoDB: The Developer Data Platform | MongoDB. If you have a server online you can sign in to it.

No worries if you don’t have created a MongoDB server.

Just click on sign up, fill out the forum they provide and Sign Up with a Google account.

image by author

After that, you have to accept the terms and policies below and you have to give answers to the forum coming next.

image by author
image by author
image by author

Create your server with the default setting they have provided. Click on create the cluster.

Go to DB, and can see the default cluster as Clustor0. Then, click on cluster and go to the collection tab where we store the data of our application.

image by author

It’s time to do initial configurations. We need at least one user to connect with the DB. For that go to the Database Access tab and Add New Database User.

image by author

To add a new user you will get a tab like below.

image by author

Then we have to configure the Network Access. Go to the Network Access tab and insert 0.0.0.0/0 as the Access List Entry to allow access from anywhere.

image by author
image by author

Yeah super cool…😎 It’s time to connect the DB with the server. So, will go back to our application again.

As the first step creates a .env file. Then we need to get access to our database. Then click on connect -> Connect your application in the cluster we created earlier.

image by author

And copy the connection URL to your clipboard.

image by author

Here you have to replace the admin with the user role you have already created and the password also should be replaced which corresponds to the user role.

MONGO_URL=mongodb+srv://admin:<password>@questionbank.xgxrf.mongodb.net/employee_db?retryWrites=true&w=majority

Then create a new file as db.js in your application to do the configuration to connect the DB as below.

const mongoose=require('mongoose')

const dotenv = require("dotenv");

dotenv.config();

const URL = process.env.MONGO_URL

module.exports=()=>{
return mongoose.connect(URL)
}

Now, import the db.js file into the server we created and call the method and handle it using call back. Then, connect the server after establishing the DB connection.

Therefore listen() method should invocation and insert the successful call back of the connection DB method.

const dbConnection = require("./db.js");

dbConnection()
.then(() => {
console.log("DB is connected!!")
app.listen(3000, () => console.log("Server is started on 3000"));
})
.catch((err) => console.log(err));

Below you can see the index.js(server) file after connecting the DB successfully.

image by author
image by author

Oh no… There is a warning… Will try to remove the warning.

mongoose.set('strictQuery', false); only correctly disables strict query behavior if you run it before the schemas are created. After the schemas are created, changes to this property are ignored. Then add this code line to the db.js file.

mongoose.set("strictQuery", false);

Yeah, the warning is disappeared…

Wow… Super cool… we have done it…😎😋

Guys, I think it would be better to have a break. I will come with Part 03 soon. There we are to create controllers, insert data to the DB, and… many more things….👧

Link to: Node.js API + MongoDB CRUD Operations | Part 03

Until then bye to you…👋👋👋

--

--