Update / Edit Data In MongoDB: Node.js

Today lets look at editing and updating user entered data via Node.js application.

Related Read:
Connecting To MongoDB Using Mongoose: Node.js
Save data To MongoDB: Node.js
Fetch Data From MongoDB: Node.js
Fetch Individual User Data From MongoDB: Node.js
..please go through these 4 tutorials before proceeding further. It’ll take less than 20 min

link to individual profile page
view/index.jade

ul
each user in users
 li
  a(href='/user/#{user._id}') #{user.name}

This displays list of all the users with their name, hyper-linked with their email id(present inside _id).

Adding Edit link
view/show.jade

#{user.name}

ul li Age: #{user.age} li Email: #{user._id} ul li a(href="/user/#{user._id}/edit") Edit

This adds Edit link below each individual user information.

Edit Form
view/edit-form.jade

Editing #{user.name}'s profile!

form(method="POST", action="/user/#{user._id}") input(type="hidden", name="_method", value="PUT") p Name: input(type="text", name="name", value="#{user.name}") p Age: input(type="number", name="age", value="#{user.age}") p input(type="submit")

It shows a message letting know the user, which user’s information they are editing. Also it fills the previous values for name and age. You can find a hidden field with the name _method, which helps to override POST method, and facilitates PUT method.

Edit and Update Routes
app.js

app.get('/user/:id/edit', function(req, res){
 res.render('edit-form', {user: req.userId});
});

app.put('/user/:id', function(req, res){
 user.update({_id: req.params.id},
                    {
         name: req.body.name,
      age   : req.body.age
      }, function(err, docs){
     if(err) res.json(err);
    else    res.redirect('/user/'+req.params.id);
    });
});

app.param('id', function(req, res, next, id){
 user.findById(id, function(err, docs){
   if(err) res.json(err);
   else
   {
    req.userId = docs;
    next();
   }
  }); 
});

Here id matches the param call, and using findById() method of mongoose, it fetches all the users present in the database. Once we call next(), it passes the control to next level. At /user/:id/edit route, we render edit-form.jade file and pass it with user information, to be filled inside the form input fields.

Once the user makes changes to the values and submits the form, all the values are passed to /user/:id route. In /user/:id route, we call update() method and specify which user information has to be updated in its first parameter, in second parameter we specify all the fields to be updated, and the third parameter is a callback method and it only takes error object as argument.

Using findByIdAndUpdate() method
app.js

app.put('/user/:id', function(req, res){
 user.findByIdAndUpdate({_id: req.params.id},
                    {
         name: req.body.name,
      age   : req.body.age
      }, function(err, docs){
     if(err) res.json(err);
    else
    { 
       console.log(docs);
       res.redirect('/user/'+req.params.id);
     }
    });
});

Syntax of findByIdAndUpdate() method is same as that of update(), only difference is, findByIdAndUpdate() returns the result object as well as error object to the callback method. We can make use of result object to our advantage – in our above example, I’m simply illustrating the concept by logging the result object on to the console window.

Update / Edit Document In MongoDB: Node.js



YouTube Link: https://www.youtube.com/watch?v=wdja8tYsvK8 [Watch the Video In Full Screen.]



Full Source Code: with findByIdAndUpdate() method
app.js

var express = require('express');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

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

var Schema = new mongoose.Schema({
 _id    : String,
 name: String,
 age   : Number
});

var user = mongoose.model('emp', Schema);

app.get('/user/:id/edit', function(req, res){
 res.render('edit-form', {user: req.userId});
});

app.put('/user/:id', function(req, res){
 user.findByIdAndUpdate({_id: req.params.id},
                    {
         name: req.body.name,
      age   : req.body.age
      }, function(err, docs){
     if(err) res.json(err);
    else
    { 
       console.log(docs);
       res.redirect('/user/'+req.params.id);
     }
    });
});

app.param('id', function(req, res, next, id){
 user.findById(id, function(err, docs){
   if(err) res.json(err);
   else
   {
    req.userId = docs;
    next();
   }
  }); 
});


app.get('/user/:id', function(req, res){
 res.render('show', {user: req.userId});
});

app.get('/view', function(req, res){
 user.find({}, function(err, docs){
  if(err) res.json(err);
  else    res.render('index', {users: docs})
 });
});

app.post('/new', function(req, res){
 new user({
  _id    : req.body.email,
  name: req.body.name,
  age   : req.body.age    
 }).save(function(err, doc){
  if(err) res.json(err);
  else    res.redirect('/view');
 });
});

var server = http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

/ for new entries
/view for viewing all the users
/user/:id to see individual user information
/user/:id/edit to edit individual user information

Note:
In real-world applications, it would make sense if only you are allowed to edit and update your data. To accomplish this – once the user logs in, store her _id value in a session variable. While the user issues an edit/update for a particular id, make sure the id she is requesting for edit/update matches with that present in the session variable!