REST API Using Node.js, MongoDB, And Express

In this article, we will be focusing on one of the most interesting and recent topics; i.e., implementing REST API using Node.js and MongoDB.

To start learning any new thing, knowing 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 here.

Here it is what you will see after navigating to the above link. The version might be different in your case when you read this.

REST API Using Node.js, MongoDB And Express 

The next step is to perform the following steps in your command prompt.

npm install express-generator -g ( -g stands for global)

REST API Using Node.js, MongoDB And Express 

Next, create an empty folder and hit express in it. It will create an application ready for us.

REST API Using Node.js, MongoDB And Express 

The next step is to install CORS (Cross-Origin Resource Sharing). It will allow our API to be called from any URL. Hit the following command.

cmd>npm install cors –save

REST API Using Node.js, MongoDB And Express 

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 to help us manage our database in a structural way. So, to install Mongoose in our existing application hit this command.

cmd>npm install mongoose –save

REST API Using Node.js, MongoDB And Express 

Now, the last step is to install the rest of the dependencies in our application by firing the command -

cmd>npm install

REST API Using Node.js, MongoDB And Express 

So, we are done with all the adjustments required 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.

REST API Using Node.js, MongoDB And Express 

Before we actually start writing our code, first start the MongoDB server. Open 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 is how the server will be started. And keep it in running mode until the end.

REST API Using Node.js, MongoDB And Express 

Next, open another command prompt and hit the command mongo.

REST API Using Node.js, MongoDB And Express 

After that, create any database of your choice. In my case, I am creating productdb database.

REST API Using Node.js, MongoDB And Express 

Now, let’s get back to the implementation. Create a new file named dbconnection.js and insert the below code in it.

  1. const mongoose=require('mongoose');  
  2. const url="mongodb://localhost:27017/productdb";  
  3.   
  4. mongoose.connect(url,{useNewUrlParser:true},function(err){  
  5.     if(err){  
  6.         console.log('Error in connection');  
  7.     }  
  8.     else{  
  9.         console.log('Connected!');  
  10.     }  
  11. })  
  12. module.exports=mongoose;  

Here, I have created mongoose variable, which will use the mongoose package which we have installed previously. Another variable named url 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 (ofcourse, you can give any name). And, create a new file named product.js.

  1. const db=require('../dbconnection');  
  2.   
  3. const productSchema=db.Schema({  
  4.     name:{type:string,required:true},  
  5.     price:{type:number,required:true}  
  6. });  
  7.   
  8. module.exports=db.model('Product',productSchema);  

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 fields, 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.

  1. var express=require('express');  
  2. var router=express.Router();  
  3. var product=require('../Models/product');  
  4.   
  5. router.post('/',function(req,res,next){  
  6.     const prod=new product({  
  7.         name:req.body.name,  
  8.         price:req.body.price  
  9.     });  
  10.     prod.save(function(err,result){  
  11.         if(err){  
  12.             res.json(err);  
  13.         }  
  14.         else{  
  15.             res.json(result);  
  16.         }  
  17.     });  
  18. });  
  19. module.exports=router;  

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 a 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.

REST API Using Node.js, MongoDB And Express 

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 the second is the appropriate route name which you want to call on the request of the url.

Say, for example if 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, it's /product and the name of the variable which holds the imported route. At the end, our app.js file will look like this.

  1. var createError = require('http-errors');  
  2. var express = require('express');  
  3. var path = require('path');  
  4. var cookieParser = require('cookie-parser');  
  5. var logger = require('morgan');  
  6. var cors=require('cors');  
  7. var indexRouter = require('./routes/index');  
  8. var usersRouter = require('./routes/users');  
  9. var product=require('./routes/product_routes');  
  10. var app = express();  
  11.   
  12. // view engine setup  
  13. app.set('views', path.join(__dirname, 'views'));  
  14. app.set('view engine''jade');  
  15. app.use(cors());  
  16. app.use(logger('dev'));  
  17. app.use(express.json());  
  18. app.use(express.urlencoded({ extended: false }));  
  19. app.use(cookieParser());  
  20. app.use(express.static(path.join(__dirname, 'public')));  
  21.   
  22. app.use('/', indexRouter);  
  23. app.use('/users', usersRouter);  
  24. app.use('/product',product);  
  25. // catch 404 and forward to error handler  
  26. app.use(function(req, res, next) {  
  27.   next(createError(404));  
  28. });  
  29.   
  30. // error handler  
  31. app.use(function(err, req, res, next) {  
  32.   // set locals, only providing error in development  
  33.   res.locals.message = err.message;  
  34.   res.locals.error = req.app.get('env') === 'development' ? err : {};  
  35.   
  36.   // render the error page  
  37.   res.status(err.status || 500);  
  38.   res.render('error');  
  39. });  
  40.   
  41. module.exports = app;  

 So, we are done with almost everything. Next, open up your terminal and hit the command npm start to start our node.js server.

REST API Using Node.js, MongoDB And Express 

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.

REST API Using Node.js, MongoDB And Express 

As you can see, the post method gives us the unique ID of the data inserted last. Now, let’s get back to our application and let’s work towards the get service. Add this code into your route.

  1. router.get('/',function(req,res,next){  
  2.     product.find(function(err,docs){  
  3.         if(err){  
  4.             res.json(err);  
  5.         }  
  6.         else{  
  7.             res.json(docs);  
  8.         }  
  9.     });  
  10. });  

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 other documents (records).

REST API Using Node.js, MongoDB And Express 

Lastly, let’s create delete method.

  1. router.delete('/:id',function(req,res,next){  
  2.     product.deleteOne({_id:req.params.id},function(err,result){  
  3.         if(err){  
  4.             res.json(err);  
  5.         }  
  6.         else{  
  7.             res.json(result);  
  8.         }  
  9.     });  
  10. });  

Now, notice that delete method does have an id. So our URL will be localhost:3000/ID. The 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 the delete method such as, delete, deleteOne, deleteMany. You can choose according to your need. In my case, I have chosen the deleteOne method, which takes a condition. In my case, I have supplied deleted id which you get in the form of the request from the user. This is how you can perform the delete operation.

REST API Using Node.js, MongoDB And Express 

That’s it! I hope you find this article helpful!

Source code