REST API Using Node.js, MongoDB, And Express

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.

Download

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

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

Generator

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

Empty folder

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

Command

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.

npm install mongoose --save

API

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

cmd>npm install

Install

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.

Package

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.

Server

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

 Command prompt

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

Product

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

const mongoose = require('mongoose');
const url = "mongodb://localhost:27017/productdb";

mongoose.connect(url, { useNewUrlParser: true }, function(err) {
    if (err) {
        console.log('Error in connection');
    } else {
        console.log('Connected!');
    }
});

module.exports = mongoose;

Here, I have created a mongoose variable, which will use the mongoose package that we have installed previously. Another variable named urlwill 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.

const db = require('../dbconnection');

const productSchema = db.Schema({
    name: { type: string, required: true },
    price: { type: number, required: true }
});

module.exports = db.model('Product', productSchema);

In the above code, we first 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 their 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, name it product_routes.js, and add the following code.

var express = require('express');
var router = express.Router();
var product = require('../Models/product');

router.post('/', function (req, res, next) {
    const prod = new product({
        name: req.body.name,
        price: req.body.price
    });
    prod.save(function (err, result) {
        if (err) {
            res.json(err);
        } else {
            res.json(result);
        }
    });
});

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 have 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 that 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.

Resource

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 a user requests localhost:3000/user, then /user is our URL and user_routes will be the route that we want to call. In our case, it's /product and the name of the variable that holds the imported route. At the end, our app.js file will look like this.

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var product = require('./routes/product_routes');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/product', product);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

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.

 Terminal

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.

Inserted

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.

router.get('/', function(req, res, next) {
    product.find(function(err, docs) {
        if (err) {
            res.json(err);
        } else {
            res.json(docs);
        }
    });
});

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

Document

Lastly, let’s create a delete method.

router.delete('/:id', function(req, res, next) {
    product.deleteOne({ _id: req.params.id }, function(err, result) {
        if (err) {
            res.json(err);
        } else {
            res.json(result);
        }
    });
});

Now, notice that the 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 that was returned when we have inserted the data.

Moreover, Mongoose does have many options with the delete method such as, delete, deleteOne, and deleteMany. You can choose according to your needs. In my case, I have chosen the delete method, which takes a condition. In my case, I have supplied a deleted ID which you get in the form of a request from the user. This is how you can perform the delete operation.

Send

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

Source code


Similar Articles