REST API Tutorial

Restful CRUD API with Express, MongoDB and Mongoose

This is another nodejs and express.js tutorial that shows how to use Mongodb and Mongoose ORM to create CRUD operations.

The Mongodb is a popular no-SQL database that is open source.

Mongoose is an object-relational mapping (ORM) framework that includes useful ways for working with Mongodb collections.

I have already shared Node js Rest Api to Add, Edit and Delete Record from MySQL Using Express JS. I am assuming you have installed mongodb into your server.

Mongodb and Mongoose

MongoDB will be the database, and mongoose ORM will be used to perform actions on Mongodb models. I’ll make an HTTP REST call to get information about mongodb collections, add new records in mongodb, update existing records in mongodb, and destroy collections.

This node js tutorial will cover the following features:

  • How to create a database connection with Mongodb.
  • How to create a Model using Mongoose.
  • How to create a collection in Mongodb using Mongoose.
  • How to delete collection in Mongodb using Mongoose.
  • How to update Collection in Mongodb using Mongoose.
  • Creating CRUD operation REST API using Node, ExpressJS, MongoDB, and Mongoose.

Rest End Points

The Node js Rest API details are as follows:

Route Method Type Posted JSON Description
/employees GET JSON Get all employees data
/employees/{id} GET JSON Get a single employee data
/employees POST JSON {"employee_name": "Rachel", "employee_age": "44", "employee_salary" : "4521"} Insert new employee record into database
/employees PUT JSON {"employee_name": "Rachel", "employee_age": "56", "employee_salary" : "5421", "id":44} Update employee record into database
/employees DELETE JSON {"id" : 9} Delete particular employee record from database

Node JS Rest API

Let’s create a folder ‘nodejs-restapi-mongoose’ in the nodejs workspace.This is our nodejs project name and will have all files.

  • package.json: This file will have all nodejs dependencies module for this example.
  • config/database.js: This file will be used for database connection parameters for Mongodb.
  • model/employee.js: This file will be used to create an employee schema and model.
  • main.js: This file will use to create nodejs application server and routes url.
  • node_modules : This folder will contain all nodejs packages.

install dependencies

We will create a package.json file into ‘nodejs-restapi-mongoose’ folder and add the below JSON into this file.

{
  "name": "nodejs-mongoose-example",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": {
    "name": "Adam",
    "email": "restapi2example@gmail.com",
    "url": "https://www.restapiexample.com/"
  },
  "license": "MIT",
  "dependencies": {
    "express": "~4.13.2",
    "mongoose": "~3.6.2",
    "body-parser": "~1.14.1",
    "method-override": "~2.3.5"
  }
}

We’ll open a command prompt and navigate to the 'nodejs-restapi-mongoose-example' folder, where we’ll run the command below to install the required modules in the ‘node modules’ folder.

d:\nodejs-restapi-mongoose-example > npm install

Create Database Connection

We’ll put a database.js connection file in the config folder, then add the mongodb connection URL like this:

// config/database.js
module.exports = {
    url : 'mongodb://localhost/'
};

Create MongoDB Model

We’ll save the employee.js model to the model folder, then construct a schema and register the Employee model.

// load mongoose since we need it to define a model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
EmpSchema = new Schema({
    name : String,
    salary : Number,
    age : Number
});
module.exports = mongoose.model('Employee', EmpSchema);

In the above code, we have created an instance of mongoose and schema. We have defined our employee table schema here.

Create server file

created a main project entry server.js file.We’ll add dependent modules to this file.Added below code into the server.js file.

var express  = require('express');
var mongoose = require('mongoose');
var app      = express();
var database = require('./config/database');
var bodyParser = require('body-parser');         // pull information from HTML POST (express4)
var methodOverride = require('method-override');

var port     = process.env.PORT || 8888;
app.use(bodyParser.urlencoded({'extended':'true'}));            // parse application/x-www-form-urlencoded
app.use(bodyParser.json());                                     // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride());

var Employee = require('./models/employee');

mongoose.connect(database.url);

app.listen(port);
console.log("App listening on port : " + port);

Rest Api to fetch all records

We’ll use a GET Rest Request to get all of MongoDB’s employee records. To get data from the employee database, we’ll use a mongodb query and send JSON data to the client as a response object.

//get all employee data from db
app.get('/api/employees', function(req, res) {
    // use mongoose to get all todos in the database
    Employee.find(function(err, employees) {
        // if there is an error retrieving, send the error otherwise send data
        if (err)
            res.send(err)
        res.json(employees); // return all employees in JSON format
    });
});

Employee.find is a method for retrieving all records from a database. The res.end() method uses the JSON.stringify() method to transmit data to the client as a json string.

Now, using a browser, go to http://localhost:8888/employee rest api address to receive a list of all employees in the Mongo database.

I’ll cover the rest of the functionality in the next tutorial.

If you have requirements that needs our attentioN

Please feel free to contact us

We would love to hear from you

Share with your network

Facebook
Twitter
LinkedIn
WhatsApp
Email

This tutorial is intended to cover all the essentials steps and insights to understand Restful CRUD API with Express, MongoDB and Mongoose

Genislab Technologies

Learn further