Node.js, Express.js, Mongoose.js, and MongoDB is a great combination for building easy and fast REST API. You will see how fast that combination than other existing frameworks because of Node.js is a packaged compilation of Google’s V8 JavaScript engine and it works on non-blocking and event-driven I/O. Express.js is a Javascript web server that has the complete function of web development including REST API.

Jumps to the steps:

In this tutorial, we will create a Node REST API of Product data. The Product accessible through the Express REST API with the method of GET, POST, PUT, and DELETE. The Express route from the request of REST API to the Mongoose query that points to the Mongoose model and persists to the MongoDB database.

Before we begin, make sure you have installed all the tools that required.

Node.js MongoDB Script/Text Editor or IDE

You can watch the video tutorial from our YouTube channel.

In this tutorial, we will work using Terminal and Atom as the text editor. For Windows users, you can work using the Node.js command line. We started this Node.js, Express.js, Mongoose.js and MongoDB tutorial from scratch and then continue a quicker way using the Node-Restful library. Let's begin.



Create Express.js Project and Install Required Modules

Open your terminal or node command line the go to your projects folder. First, install express-generator using this command.

sudo npm install express-generator -g

Next, create an Express.js app using this command.

express node-rest-api -e

This will create the Express.js project with the EJS view instead of the Jade view template because using the '-e' parameter. Next, go to the newly created project folder then install node modules.

cd node-rest-api && npm install

Run the server by this command.

npm start

You will see the log like this in the terminal.

Open your browser then pointing to 'localhost:3000', if you see like the image below then your server is ready.



Add Mongoose.js Module as ORM for MongoDB

Why using Mongoose MongoDB ODM? Because Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box. Next, stop node by push CTRL+C on the keyboard. Type this command to install the Mongoose.js module.

npm install mongoose --save

Before running your server again, make sure MongoDB server is running. Open another terminal, then type this command to start MongoDB server.

mongod

Now, open and edit app.js in the root of the project folder using your favorite text editor or IDE. Declare mongoose in require sections.

var mongoose = require('mongoose');

Use mongoose with native Node Promise.

mongoose.Promise = global.Promise;

Create a connection to MongoDB.

mongoose.connect('mongodb://localhost/product') .then(() => console.log('connection succesful')) .catch((err) => console.error(err));

Next, run the node app again.

npm start

You should see this message on the terminal. It's mean the connection to MongoDB is successful.

> [email protected] start /Users/didin/Documents/NodeApps/node-rest-api > node ./bin/www connection successful

Create Product Mongoose Model

Now, create models directory and javascript file as the model. Before doing that, stop node server by pushing the CTRL+C key in the terminal.

mkdir models touch models/Product.js

Open and edit Product.js file then add these lines of codes.

var mongoose = require('mongoose'); var ProductSchema = new mongoose.Schema({ prod_name: String, prod_desc: String, prod_price: Number, updated_at: { type: Date, default: Date.now }, }); module.exports = mongoose.model('Product', ProductSchema);

That Schema will mapping to MongoDB collections called product. If you want to know more about Mongoose Schema Datatypes you can find it here.



Create Routes for the REST API endpoint

The REST API that we build will have the following functions.

Method Endpoints Notes GET /product Get all products GET /product/:id Get single product POST /product Add product PUT /product/:id Update product DELETE /product/:id Delete product

To achieve that, add the javascript file to the routes folder.

touch routes/products.js

Open and edit routes/products.js then add these lines of codes.

var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var Product = require('../models/Product.js'); /* GET ALL PRODUCTS */ router.get('/', function(req, res, next) { Product.find(function (err, products) { if (err) return next(err); res.json(products); }); }); /* GET SINGLE PRODUCT BY ID */ router.get('/:id', function(req, res, next) { Product.findById(req.params.id, function (err, post) { if (err) return next(err); res.json(post); }); }); /* SAVE PRODUCT */ router.post('/', function(req, res, next) { Product.create(req.body, function (err, post) { if (err) return next(err); res.json(post); }); }); /* UPDATE PRODUCT */ router.put('/:id', function(req, res, next) { Product.findByIdAndUpdate(req.params.id, req.body, function (err, post) { if (err) return next(err); res.json(post); }); }); /* DELETE PRODUCT */ router.delete('/:id', function(req, res, next) { Product.findByIdAndRemove(req.params.id, req.body, function (err, post) { if (err) return next(err); res.json(post); }); }); module.exports = router;

Next, open and edit app.js then add product route as require after users require.

var products = require('./routes/products');

Then add use after use of users.

app.use('/products', products);



Test REST API Endpoints

After everything is ready, this time to testing our created Node.js, Express.js, Mongoose.js and MongoDB REST API. There are so many tools for testing REST API, but for now, we are testing using CURL from the terminal.

We start with Add/Save product data first. Open a new terminal tab or windows then type this command.

curl -i -X POST -H "Content-Type: application/json" -d '{ "prod_name":"XBox One","prod_desc":"New Microsoft XBox One, the latest games console","prod_price": 520 }' localhost:3000/products

If you get a response like below, then you save a new product successfully.

HTTP/1.1 200 OK X-Powered-By: Express Content-Type: application/json; charset=utf-8 Content-Length: 185 ETag: W/"b9-ymiFjoNdt5wABoii1CiYbg" Date: Sun, 19 Feb 2017 03:30:35 GMT Connection: keep-alive {"__v":0,"prod_name":"XBox One","prod_desc":"New Microsoft XBox One, the latest games console","prod_price":520,"_id":"58a9115abed027087df7133b","updated_at":"2017-02-19T03:30:34.415Z"}

We can create the same POST with different data to populate more records to product collection.

curl -i -X POST -H "Content-Type: application/json" -d '{ "prod_name":"Sony PS 4","prod_desc":"Sony playstation 4","prod_price": 580 }' localhost:3000/products

Next, we are testing to get all product data using this command.

curl -i -H "Accept: application/json" localhost:3000/products

That command will response to products data with JSON format.

HTTP/1.1 200 OK X-Powered-By: Express Content-Type: application/json; charset=utf-8 Content-Length: 344 ETag: W/"158-V1WRYZrNC8yW7HFEfOSSew" Date: Sun, 19 Feb 2017 03:34:26 GMT Connection: keep-alive [{"_id":"58a9115abed027087df7133b","prod_name":"XBox One","prod_desc":"New Microsoft XBox One, the latest games console","prod_price":520,"__v":0,"updated_at":"2017-02-19T03:30:34.415Z"},{"_id":"58a91204bed027087df7133c","prod_name":"Sony PS 4","prod_desc":"Sony playstation 4","prod_price":580,"__v":0,"updated_at":"2017-02-19T03:33:24.941Z"}]

Next, we are testing to get one product by id using this command.

curl -i -H "Accept: application/json" localhost:3000/products/58a91204bed027087df7133c

The response should be like this.

HTTP/1.1 200 OK X-Powered-By: Express Content-Type: application/json; charset=utf-8 Content-Length: 156 ETag: W/"9c-NYW3p4BkPVbiNf05Ezj+zA" Date: Sun, 19 Feb 2017 03:45:48 GMT Connection: keep-alive {"_id":"58a91204bed027087df7133c","prod_name":"Sony PS 4","prod_desc":"Sony playstation 4","prod_price":580,"__v":0,"updated_at":"2017-02-19T03:33:24.941Z"}

Next, we are editing and update one of a product by id using this command. First, copy id from one of product from the response before then paste it as the parameter.

curl -i -X PUT -H "Content-Type: application/json" -d '{"prod_desc":"Microsoft XBox One"}' localhost:3000/products/58a9115abed027087df7133b

It should response like this.

HTTP/1.1 200 OK X-Powered-By: Express Content-Type: application/json; charset=utf-8 Content-Length: 185 ETag: W/"b9-k9Wipgusc9JVZAMyHgjVXw" Date: Sun, 19 Feb 2017 03:38:24 GMT Connection: keep-alive {"_id":"58a9115abed027087df7133b","prod_name":"XBox One","prod_desc":..

Finally, we are testing to delete one product by id using this command.

curl -i -X DELETE localhost:3000/products/58a9115abed027087df7133b

It will response like this and the product with that id will be removed from product collection.

HTTP/1.1 200 OK X-Powered-By: Express Content-Type: application/json; charset=utf-8 Content-Length: 155 ETag: W/"9b-pP1KXaQhyqcMkvBlLa6pFQ" Date: Sun, 19 Feb 2017 03:41:54 GMT Connection: keep-alive {"_id":"58a9115abed027087df7133b","prod_name":"XBox One","prod_desc":"Microsoft XBox One","prod_price":520,"__v":0,"updated_at":"2017-02-19T03:30:34.415Z"}

Quick REST API Creation using Node-Restful Library

There are so many methods and libraries for creating REST API quicker and elegant. One of them that I found is the Node-Restful library that you can find on Github. Just add the library using the NPM command.

npm install node-restful --save

Open and edit app.js on the root of the project. Add require a line for Node-Restful and Method-Override.

var restful = require('node-restful'); var methodOverride = require('method-override');

Change "bodyParse extended" value to true then add these lines.

app.use(bodyParser.urlencoded({'extended':'true'})); app.use(bodyParser.json({type:'application/vnd.api+json'})); app.use(methodOverride());

Create a mongoose model that use together with the Node-Restful library. Right now we are creating a "category" model.

var Category = app.resource = restful.model('category', mongoose.Schema({ cat_name: String, })) .methods(['get', 'post', 'put', 'delete']); Category.register(app, '/category');

Run again the app and test it using the previous way for testing REST API. You can compare it with another framework that I write on this website. By the way, this the full source code on Github.

That just the basic. If you need more deep learning about Node.js, Express.js, PostgreSQL, Vue.js and GraphQL or related you can take the following cheap course:

Thanks.