Make your own REST API with MongoDB with Mongoose, Express.js, and Node.js
Node.js, Express.js, Mongoose.js and MongoDB is that the nice combination for building simple and quick REST API. you may see how fast that combination than other existing frameworks because of Node.js could be a prepacked compilation of Google’s V8 JavaScript engine and it works on non-blocking and event-driven I/O. Express.js is javascript net server that has complete function of web development including REST API.Before we begin, confirm you’ve got put in all tools that required.
- Node.js
- MongoDB
- Script/Text * VisualStudio Code Editor / Atom / Bracket / Editor or IDE
this tutorial, we’ll work using Terminal and your favorite code editor as the text editor. For Windows user, you’ll be able to work exploitation Node.js command. we have a tendency to started this Node.js, Express.js, Mongoose.js and MongoDB tutorial from scratch and then continue a quicker method using Node-Restful library. Let’s begin.
Step 1. Create Express.js Project along w/d Required Modules
Start your CLI terminal or node command line the go to your projects folder. First, install express generator using this command.
1 |
$ sudo npm install express-generator -g |
Next, create an Express.js app using this command.
1 |
$ express node-rest-api -e |
1 |
$ cd node-rest-api && npm install |
To run the server
1 |
$ npm start |
Shows like this in your the terminal.
1 2 |
$ node-rest-api@0.0.0 start /Users/didin/Documents/NodeApps/node-rest-api $ node ./bin/www |
Step 2. Add Mongoose.js Module as ORM for MongoDB
Stop node by push CTRL+C on the keyboard. Type this command to install Mongoose.js module.
1 |
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.
1 |
mongod |
Now, open and edit app.js in the root of project folder using your favorite text editor or IDE. Declare mongoose in require sections.
1 |
var mongoose = require('mongoose'); |
Use mongoose with native Node Promise.
1 |
mongoose.Promise = global.Promise; |
Create a connection to MongoDB.
1 2 3 |
mongoose.connect('mongodb://localhost/product') .then(() => console.log('connection succesful')) .catch((err) => console.error(err)); |
Next, run the node app again.
1 |
npm start |
You should see this message on the terminal. It’s mean connection to MongoDB is successful.
1 2 3 4 |
> node-rest-api@0.0.0 start /Users/didin/Documents/NodeApps/node-rest-api > node ./bin/www connection successful |
Step 3. Create Product Mongoose Model
Create models directory and javascript file as the model. stop node server by pushing CTRL+C key in the terminal.
1 2 |
mkdir models touch models/Product.js |
Open and edit Product.js file the add this lines of codes.
1 2 3 4 5 6 7 8 9 10 |
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.
Step 4. Create Routes for REST API endpoint
The REST API that will have 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 |
Add the javascript file to routes folder.
1 |
touch routes/products.js |
Edit routes/products.js then add this lines of codes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
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; |
Edit app.js then add product route as require after users require.
1 |
var products = require('./routes/products'); |
Add use after use of users.
1 |
app.use('/products', products); |
Step 5. 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 new terminal tab or windows the type this command.
1 |
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 the response like below, then you save new product successfully.
1 2 3 4 5 6 7 8 9 |
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 record to product collection.
1 |
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 products data using this command.
1 |
curl -i -H "Accept: application/json" localhost:3000/products |
That command will response products data with JSON format.
1 2 3 4 5 6 7 8 9 |
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.
1 |
curl -i -H "Accept: application/json" localhost:3000/products/58a91204bed027087df7133c |
The response should be like this.
1 2 3 4 5 6 7 8 9 |
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.
1 |
curl -i -X PUT -H "Content-Type: application/json" -d '{"prod_desc":"Microsoft XBox One"}' localhost:3000/products/58a9115abed027087df7133b |
It should response like this.
1 2 3 4 5 6 7 8 9 |
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 for delete one product by id using this command.
1 |
curl -i -X DELETE localhost:3000/products/58a9115abed027087df7133b |
It will response like this and product with that id will be removed from product collection.
1 2 3 4 5 6 7 8 9 |
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"} |
Step 6. Quick REST API Creation using Node-Restful Library
There are so many method and library 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 npm command.
1 |
npm install node-restful --save |
Open and edit app.js on the root of the project. Add require line for Node-Restful and Method-Override.
1 2 |
var restful = require('node-restful'); var methodOverride = require('method-override'); |
Change “bodyParse extended” value to true then add this lines.
1 2 3 |
app.use(bodyParser.urlencoded({'extended':'true'})); app.use(bodyParser.json({type:'application/vnd.api+json'})); app.use(methodOverride()); |
Create mongoose model that use together with Node-Restful library. Right now we are creating “category” model.
1 2 3 4 5 6 |
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 previous way for testing REST API.