Home » Node Js » REST using Node/Express & Mongoose

REST using Node/Express & Mongoose

NodeJS is fast growing language in today environment. For web their are several frameworks but Express web framework  is most used framework for web development in node js.

So how to make a sample Rest API in express / Node JS ?

First setup express using npm. So we use following commands to get npm init & require packages install.

# add package json
$ npm init

$ npm install --save express 
$ npm install --save mongoose body-parser

Above commands install express framework in node modules. Then it install http request parser package plus ODM package for mongo db called mongoose. Now it is time to do some coding. First create main application file app.js & put following code.

var express = require('express');
var app = express();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');


// var UserController = require('./controllers/UserController');
// app.use('/users', UserController);

var port = process.env.PORT || 3000;
var server = app.listen(port, function() {
      console.log('Express server listening on port ' + port);
});

module.exports = app;

Update package.json to set tell about main script

"scripts": {
       "start": "node app.js"
 }

You can run this code by

$ npm start

Which start the server at 3000 port. You can check http://localhost:3000 which show “Cannot GET /” because we did not setup router. So we add a User Module. for this we need to add controller & model. So create two directories controllers & models for better code maintaining.  Add Following mongoose based code in models/User.js file.

var mongoose = require('mongoose');
var UserSchema = new mongoose.Schema({
    name: String,
    email: String,
    password: String
});
mongoose.model('User', UserSchema);
module.exports = mongoose.model('User');

Now Setup controller file controllers/UserController.js which also work as router for User APIs.

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: true }));

var User = require('../models/User');

router.post('/', function (req, res) {

    User.create({
        name : req.body.name,
        email : req.body.email,
        password : req.body.password
    },
    function (err, user) {
        if (err) return res.status(500).send("There was a problem adding the information to the database.");
        res.status(200).send(user);
    });

});

// RETURNS ALL THE USERS IN THE DATABASE
router.get('/', function (req, res) {

    User.find({}, function (err, users) {
        if (err) return res.status(500).send("There was a problem finding the users.");
        res.status(200).send(users);
     });

});

// RETURNS USER DETAILS IN THE DATABASE
router.get('/:id', function (req, res) {

    User.findOne({"_id":req.params.id}, function (err, users) {
        if (err) return res.status(500).send("There was a problem finding the users.");
        res.status(200).send(users);
    });

});

// UPDATE USER DETAILS IN THE DATABASE
router.put('/:id', function (req, res) {

    User.update({"_id":req.params.id}, {
        name : req.body.name,
        email : req.body.email,
        password : req.body.password
    }, function (err, users) {
        if (err) return res.status(500).send("There was a problem finding the users.");
        res.status(200).send(users);
    });

});

// DELETE USER FROM THE DATABASE
router.delete('/:id', function (req, res) {
    User.remove({"_id":req.params.id}, function (err, users) {
        if (err) return res.status(500).send("There was a problem finding the users.");
        res.status(200).send(users);
     });

});

module.exports = router;

Now we have out two user APIs ready for insert a single record ( POST ) & get all records ( GET ). But still we need to register router with app, So uncomment lines in app.js

var UserController = require('./controllers/UserController');
app.use('/users', UserController);

Now we have http://localhost:3000/users working as POST & GET method for our APIs. We can test it by invoking respective methods via CURL CLI.

$ curl http://localhost:3000/users
$ curl -X POST -d 'email=kuldeep@gmail.com&name=Kuldeep&password=kamboj' http://localhost:3000/users

$ curl http://localhost:3000/users/5a47d942cb4f00c95de8f511

$ curl -X PUT -d 'email=kuldeepk@gmail.com&name=KuldeepK&password=kamboj' http://localhost:3000/users/5a47d942cb4f00c95de8f511

$ curl -X DELETE  http://localhost:3000/users/5a47d942cb4f00c95de8f511

 

Advertisements

One thought on “REST using Node/Express & Mongoose

  1. Pingback: Node REST API Testing with Jasmine | Kuldeep15's Weblog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s