Search This Blog

2018/09/06

CRUD opeation using Mongoose & Express.js

Mongoose is an ORM for mongodb in node.js.
It provides validation of property like field is required,max length & min length of text field & many more.

we will create an express application that does CRUD operation on mongo using mongoose.


First lets create an express app

    express --view=ejs myapp

add models folder.Into models folder add user.js with following code

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;

    mongoose.connect('mongodb://localhost/palbum');

    // create a schema
    var userSchema = new Schema({
        firstname: String,
        lastname: String,
        username: { type: String, required: true, unique: true },
        password: { type: String, required: true },
        admin: { type: Boolean, default: false },
        location: { type: String, minlength: 5, maxlength: 15 },
        meta: {
        age: { type: Number, min: 5 },
        website: String
        },
        created_at: { type: Date, default: Date.now },
        updated_at: { type: Date, default: Date.now }
    });

    //instance method
    userSchema.methods.dudify = function () {
        this.name = this.name + '-dude';
        return this.name;
    };

    //static method
    userSchema.statics.findByLocation = function(location, cb) {
        return this.find({ location: new RegExp(location, 'i') }, cb);
    };

    // we need to create a model using it
    var User = mongoose.model('User', userSchema);

    // make this available to our users in our Node applications
    module.exports = {
       "User": User,
       "UserSchema":userSchema
    }

In user schema validation has been put in place over username to ensure uniqueness of username across records. "location" has been asssigned maxlength & minlength validation defaukt value has been set on created_at & updated_at.

In mongoose we can add instance method & static method."findByLocation" is static method while "dudify" is instance method.for using "dudify" we need instance of User unlike "findByLocation".

update route/users.js as follows

    var express = require('express');
    var router = express.Router();
    var User = require('../models/user').User;
    var userSchema = require('../models/user').userSchema;
    var mongoose = require('mongoose');

    /* GET users listing. */
    router.get('/', function (req, res, next) {
      res.send('respond with a resource');
    });


    router.post('/add', function (req, res, next) {
      // create a new user called chris
      var postUser = new User({
        firstname: req.body.firstname,
        lastname: req.body.lastname,
        location: req.body.location,
        meta: {
          age: req.body.age,
          website: req.body.website
        },
        username: req.body.username,
        password: req.body.password,
      });

      //dudify
      postUser.dudify(function (err, name) {
        if (err) throw err;
        console.log('Your new name is ' + name);
      });

      postUser.save(function (err) {
        if (err) throw err;
        console.log('User saved successfully!');
        res.send('User saved successfully!');
      });


    });

    router.post('/location', function (req, res, next) {
      var User = mongoose.model('User', userSchema);
      User.findByLocation(req.body.location, function (err, users) {
        console.log(users);
        res.json(users);
      });
    });

    router.get('/getAll', function (req, res, next) {
      // get all the users
      User.find({}, function (err, users) {
        if (err) throw err;

        // object of all the users
        console.log(users);
        res.json(users);
      });
    });

    router.get('/get/:username', function (req, res, next) {
      User.find({ username: req.params.username }, function (err, user) {
        if (err) throw err;

        // object of the user
        console.log(user);
        res.json(user);
      });
    });

    router.delete('/findthenremove/:username', function (req, res, next) {
      console.log("username" + req.params.username);
      User.find({ username: req.params.username }, function (err, user) {
        if (err) throw err;

        console.log(JSON.stringify(user));

        if (user == undefined || user == null) {
          res.json({
        "success": 0,
        "data": {},
        "message": "user not found!"
          });
        } else {

          // delete him
          User.deleteOne({ username:  req.params.username }, function (err) {
        if (err) return handleError(err);

        console.log('User successfully deleted!');
        res.json({
          "success": 1,
          "data": user,
          "message": "user removed!"
        });
          });

        }
      });
    });


    router.delete('/findandremove/:username', function (req, res, next) {
      console.log("username" + req.params.username);

      User.findOneAndRemove({ username: req.params.username }, function (err) {
        if (err) throw err;

        // we have deleted the user
        console.log('User deleted!');
        res.json('User deleted!')
      });
    });

    router.put('/update/:username', function (req, res, next) {
      User.updateOne({ username: req.params.username }, { password: req.body.password}, function(err, resp) {
        res.json("user password updated!");
      });
    });

    module.exports = router;

we have following endpoints

1) adding new user:
    Endpoint:http://localhost:3000/users/user
    Method:http post
    Header:Content-Type:application/json
    sample Payload:
    {
        "firstname": "Chris",
        "lastname":"harris",
        "username": "oneoneone",
        "password": "password",
        "location":"puneeee",
        "age":36,
        "website":"msdotnetbuddy.blogspot.in"
    }
   response:User saved successfully!

2)find by location:list all record with location mumbai.

    Endpoint: http://localhost:3000/users/location
    Method:post
    Header:Content-Type:application/json
    Payload:
    {
        "location":"mumbai"
    }
    Response:
    [
        {
        "meta": {
            "age": 36,
            "website": "msdotnetbuddy.blogspot.in"
        },
        "admin": false,
        "_id": "5b90e1e549999d1d073d79ca",
        "firstname": "Chris",
        "lastname": "harris",
        "location": "mumbai",
        "username": "one",
        "password": "password",
        "created_at": "2018-09-06T08:14:29.295Z",
        "updated_at": "2018-09-06T08:14:29.295Z",
        "__v": 0
        }
    ]
3) List all Records:
       Endpoint:http://localhost:3000/users/getAll
       method:get
       response:
        [
            {
            "admin": false,
            "created_at": "2018-09-06T12:02:39.372Z",
            "updated_at": "2018-09-06T12:02:39.372Z",
            "_id": "5b90dfab631d041a2aa22b47",
            "name": "Chris-dude",
            "username": "sevilayha",
            "password": "password",
            "__v": 0
            },
            {
            "admin": false,
            "_id": "5b90e0ce168db71c5bd4284a",
            "username": "chris",
            "password": "password",
            "created_at": "2018-09-06T08:09:50.942Z",
            "updated_at": "2018-09-06T08:09:50.942Z",
            "__v": 0
            },
            {
            "meta": {
                "age": 36,
                "website": "msdotnetbuddy.blogspot.in"
            },
            "admin": false,
            "_id": "5b90e1e549999d1d073d79ca",
            "firstname": "Chris",
            "lastname": "harris",
            "location": "mumbai",
            "username": "one",
            "password": "password",
            "created_at": "2018-09-06T08:14:29.295Z",
            "updated_at": "2018-09-06T08:14:29.295Z",
            "__v": 0
            },
            {
            "meta": {
                "age": 36,
                "website": "msdotnetbuddy.blogspot.in"
            },
            "admin": false,
            "_id": "5b90e6a851b57b2056e18210",
            "firstname": "Chris",
            "lastname": "harris",
            "location": "puneeee",
            "username": "oneoneone",
            "password": "password",
            "created_at": "2018-09-06T08:34:48.451Z",
            "updated_at": "2018-09-06T08:34:48.451Z",
            "__v": 0
            }
        ]
4)find single record by username
          Endpoint:http://localhost:3000/users/get/one
          Method:Get
      response:
        [
            {
            "meta": {
                "age": 36,
                "website": "msdotnetbuddy.blogspot.in"
            },
            "admin": false,
            "_id": "5b90e1e549999d1d073d79ca",
            "firstname": "Chris",
            "lastname": "harris",
            "location": "mumbai",
            "username": "one",
            "password": "password",
            "created_at": "2018-09-06T08:14:29.295Z",
            "updated_at": "2018-09-06T08:14:29.295Z",
            "__v": 0
            }
        ]
5)Delete:find & remove and coupled together rather than in two stages
    Endpoint:http://localhost:3000/users/findandremove/sevilayha
        Method:http/delete
    response:"User deleted!"

6) Delete:find & remove are decoupled
      Endpoint:http://localhost:3000/users/findthenremove/chris
      method:http/delete
      response:
    {
        "success": 1,
        "data": [
        {
            "admin": false,
            "_id": "5b90e0ce168db71c5bd4284a",
            "username": "chris",
            "password": "password",
            "created_at": "2018-09-06T08:09:50.942Z",
            "updated_at": "2018-09-06T08:09:50.942Z",
            "__v": 0
        }
        ],
        "message": "user removed!"
    }
7)Update:it updates password to new value.
    Endpoint:http://localhost:3000/users/update/oneoneone
    Header:Content-Type:application/json
    Payload:
        {
        "password":"newpassword"
        }
    Response:"user updated!"

Code of this article can be viewed at https://github.com/gitsangramdesai/mongoose-express-rest

No comments:

Post a Comment