Create REST API using MongoDB and Node.js
Hello Readers,
In this article, we will be focusing on one of the most interesting and recent topic, i.e how to implement rest API using Node.js and MongoDB. To start learning any new thing, its prerequisite is a must. Isn’t it!?
So, as a prerequisite for this, you have to be ready with Node.js installation. You can install Node.js from https://nodejs.org/en/
Here it is, what you will see after navigating to the above link. The version might be different in your case when you will read this.
Next step is to perform the following steps in your command prompt.
npm install express-generator -g ( -g stands for global)
Next, step is to create an empty folder. And hit express in it. It will create an application ready for us.
Next step is to install cors (Cross-Origin Resource Sharing). It will allow our API to be called from any URL. Hit a command:
cmd>npm install cors –save
As a next step, we will install mongoose in our application. It is a third party package, which allows our API to get connected with mongo. It allows us to create a schema, which will help us in managing our database in a structural way. So, to install mongoose in our existing application, hit a command:
cmd>npm install mongoose –save
Now, the last step is to install the rest of the dependencies in our application by firing the command:
cmd>npm install
So, we are done with all of the adjustments you need to do before starting the implementation. Now, let’s move to the practical implementation. Before actually starting the practical, open up your project in your IDE and check the file package.json to check the dependencies that we actually have installed.
Before, actually start writing our code, first start the MongoDB server. Open up your command prompt as an administrator and hit the below command.
mongod — dbpath “C:\Program Files\MongoDB\Server\4.0\data\db”
(Note: this command will run only if you have MongoDB installed in your system. If not, check out my previous blog for installation guidelines.)
Here, it is how the server will be started. And keep it in running mode till the end.
Next, open another command prompt and hit the command mongo.
After that, create any database of your choice. In my case, I am creating productdb database.
Now, let’s get back to the implementation. Create a new file named dbconnection.js and insert the below code in it.
Here, I have created mongoose variable, which will use the mongoose package which we have installed previously. Another variable named URL which will point to the database which we have created. And lastly, we will connect our mongoose to the MongoDB server. And to use this outside the file, we have exported the file.
Now, the next step is to create a folder named Models (of course, you can give any name). And, create a new file named product.js
In the above code, we first have imported the dbconnection file, which we have exported before. Next, we have created productSchema, which you can think of as a table in our SQL, which contains two field name and price having its respective type and required true property. And, again we have exported the file to use at any other place in our project.
As a next step, we have to create our routes. Create a new file inside our routes folder, and name it product_routes.js and add the following code.
In this file, we have written code to handle the post request of the user. If the request is of post type, we will insert the requested name and price inside our object which is the type of Product. While saving that object, we are having one callback function in which we will check for the error and success conditions.
As the last step, set up the app.js file. It is the first file which will be called when the user requests your backend. First, import the cors in your project, which allows our project to be cross-origin resource sharing.
Now, import the routes we have recently made. And add it to the app.use section. App.use has two arguments: one is the URL for the routes and second the appropriate route name which you want to call on the request of the URL.
Say, for example, if the user requests localhost:3000/user, then /user is our URL and user_routes will be the route which we want to call. In our case, its /product and the name of the variable which holds the imported route. In the end, our app.js file will look like this.
So, we are done with almost everything. Next, open up your terminal and hit the command npm start to start our node.js server.
There you can see it has given us the message, connected! Which means we don’t have any error in the connection. Now, we can try our services in postman. This is how you can set your post request.
As you can see, the post method gives us the unique ID of lastly inserted data. Now, let’s get back to our application and let’s work towards the get service. Add this code into your route.
Here, we have one built in method of mongoose i.e find which will find the products in our collection. It has a callback function which will give us a response in terms of error if there are any otherwise documents (records).
Lastly, let’s create the delete method.
Now, notice that delete method does have id. So our URL will be localhost:3000/ID. ID will point to the id which we want to delete. In our case, it should be that auto-generated id which was returned when we have inserted the data.
Moreover, mongoose does have many options with delete method such as delete, deleteOne, deleteMany. You can choose according to your need. In my case, I have chosen deleteOne method, which takes a condition. In my case, I have supplied that delete the id which you get in form of the request from the user. This is how you can perform the delete operation.
That’s it! I hope you find this article helpful!