How to CRUD MongoDB using NodeJS and SailsJS Part 5

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

Welcome to Part 5 of, “How to CRUD MongoDB using NodeJS and SailsJS,” the multiple-series. In Part 4, you discovered how to delete a MongoDB document based on its ID. Today’s lesson will explain how to update a document. It’s the “U” part of CRUD. Let’s start.

Prerequisites

  • Complete the instructions for Parts 1, 2, 3, and 4 of the multiple-series tutorial, “How to CRUD MongoDB using NodeJS and SailsJS.”

Use SailsJs to modify a MongoDB document

Updating, also referred to as editing, is a standard CRUD operation. You’ll need to do a controller configuration modification to give your application the performance ability to make edits for this CRUD MongoDB using NodeJs and SailsJs lesson.

Configure The Controllers

  • Open the CustomerController, and then change the code to provide the like this:
1
2
3
4
5
6
7
8
9
editcustomer: function(request, response){
Customer.findOne({id:request.params.id}).exec(function(err, customer){
if(err){
response.send(500,{error: 'Database Error'})
}
response.view('edit',{customer:customer});
});

},

Notice that the code shown above uses the method findOne(). It will locate the document with the ID that is specified in the findOne() parameter.

After it finds the document, the user can see the details for the document with that ID.

  • To save steps, go ahead and add the code within the CustomerController to execute the update:
1
2
3
4
5
6
7
8
9
10
11
12
13
updatecustomer: function(request, response){
var firstname = request.body.firstname;
var lastname = request.body.lastname;
var age = request.body.age;

Customer.update({id:request.params.id},{firstname:firstname, lastname:lastname, age:age}).exec(function(err){
if(err){
response.send(500,{error: 'Database Error'})
}
response.redirect('/customer/list');
});
return false;
}

The code shown above uses the method .update() to complete the operation. But first, it gets the form data from the request.body function. Notice the variable values are indicated (firstname, lastname, age).

After the update has completed, it will show one of two things. Either you’ll see a raised exception, or you’ll see the new value indicating the update was successful.

  • Use the command below to bring up the edit form display for the CRUD MongoDB using NodeJs and SailsJs updating record example.
1
2
3
'/customer/edit/:id':{
controller: 'CustomerController',
action: 'editcustomer',
  • Next, make a route for the action to execute the document update like this:
1
2
3
4
'/customer/update/:id':{
controller: 'CustomerController',
action: 'updatecustomer'
},

Add end-user functionality to carry out the deleting actions

The end-user will click a button on your application to perform the deleting action. To make this happen, edit the list.ejs to show the button, and then construct a file edit.ejs to carry out the delete operation.

1
2
3
4
5
6
# Customer Information Listing ID First Name Last Name Age <%= customer.id %>
<%= customer.firstname %> <%= customer.lastname %> <%= customer.age %> ["
class="btn btn-primary">Edit](https://intern.textbroker.com/customer/edit/)
<form class="d-inline" action="/customer/delete/<%= customer.id%">
  " method="POST">
</form>

Done. As you can tell by the code above [" class="btn btn-primary">Edit], the button class element for deleting a document is there. The /customer/edit is the route the ID will be sent to when the button is clicked on the end-user side.

Create a edit.ejs file for the action to follow through when clicked. Use this code here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1. [Customer](https://intern.textbroker.com/customer/list) 2. Edit # Edit
Customer Information

<form method="POST" action="/customer/update/<%=customer.id%">
  ">

  <label for="firstname">First Name</label>
  ">

  <label for="lastname">Last Name</label>
  " class="form-control">

  <label for="age">Age</label>
  " class="form-control">
</form>

Notice that the structure doesn’t vary much from the file add.ejs. This keeps things simplified on a coding level.

  • Time to test out the application. Go to a browser and input this http://localhost:1337/customer/list URL.

  • Try it out. Press the button called Edit to update a specific record in the listing.

  • You should see a response similar to this one here:

c4544bcab97d67769fe188b441e10f17.gif

Conclusion

This wraps up Part 5 of the multiple-series, “How to CRUD MongoDB using NodeJs and SailsJs,” explained how to update a MongoDB document, the “U” part of CRUD. You discovered how to add an Edit button to your application so that the end-user can perform the action on the front end. To make that happen, first, you had to configure the controller properly and create a new edit file. You then tested the application. Remember to create applications that include the functionality of CRUD basics in all of your projects from here on.

Just the Code

The sample code for the examples shown in this tutorial, Part 5 for “How to CRUD MongoDB using NodeJS and SailsJS” is displayed below for your reference. Refer to it often.

CustomerController code

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
 * CustomerController
 *
 * @description :: Server-side actions for handling incoming requests.
 * @help :: See https://sailsjs.com/docs/concepts/actions
 */


module.exports = {
  listcustomer: async (request, response) => {
    try {
      let customer = await Customer.find({});
      se.view("list", { customer });
    } catch (err) {
      response.serverError(err);
    }
  },

  addcustomer: (request, response) => {
    response.view("add");
  },

  createcustomer: (request, response) => {
    var firstname = request.body.firstname;
    var lastname = request.body.lastname;
    var age = request.body.age;

    Customer.create({
      firstname: firstname,
      lastname: lastname,
      age: age
    }).exec(function(err) {
      if (err) {
        response.send(500, { error: "Database Error" });
      }
      response.redirect("/customer/list");
    });
  },

  deletecustomer: function(request, response) {
    Customer.destroy({ id: request.params.id }).exec(function(err) {
      if (err) {
        response.send(500, { error: "Database Error" });
      }
      response.redirect("/customer/list");
    });

    return false;
  },

  editcustomer: function(request, response) {
    Customer.findOne({ id: request.params.id }).exec(function(err, customer) {
      if (err) {
        response.send(500, { error: "Database Error" });
      }
      response.view("edit", { customer: customer });
    });
  },

  updatecustomer: function(request, response) {
    var firstname = request.body.firstname;
    var lastname = request.body.lastname;
    var age = request.body.age;

    Customer.update(
      { id: request.params.id },
      { firstname: firstname, lastname: lastname, age: age }
    ).exec(function(err) {
      if (err) {
        response.send(500, { error: "Database Error" });
      }
      response.redirect("/customer/list");
    });

    return false;
  }
};

The list.ejs creation

1
2
3
4
5
6
7
# Customer Information Listing ID First Name Last Name Age <%= customer.id %>
<%= customer.firstname %> <%= customer.lastname %> <%= customer.age %> ["
class="btn btn-primary">Edit](https://intern.textbroker.com/customer/edit/)

<form class="d-inline" action="/customer/delete/<%= customer.id%">
  " method="POST">
</form>

Edit.ejs configuration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1. [Customer](https://intern.textbroker.com/customer/list) 2. Edit # Edit
Customer Information

<form method="POST" action="/customer/update/<%=customer.id%">
  ">

  <label for="
firstname">First Name</label>
  "
>

  <label for="lastname">Last Name</label>
  " class="form-control">

  <label for="
age">Age</label>
  "
class="form-control">
</form>

Route.js configuration

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
module.exports.routes = {
  // route for the homepage
  "/": { view: "pages/homepage" },

  // route for listing the customers
  "/customer/list": {
    controller: "CustomerController",
    action: "listcustomer"
  },

  // route for showing the page for adding customer
  "/customer/add": {
    controller: "CustomerController",
    action: "addcustomer"
  },

  // route for adding customer
  "/customer/create": {
    controller: "CustomerController",
    action: "createcustomer"
  },

  //route for deleting customer via id
  "/customer/delete/:id": {
    controller: "CustomerController",
    action: "deletecustomer"
  },
  // route for showing the edit form
  "/customer/edit/:id": {
    controller: "CustomerController",
    action: "editcustomer"
  },

  // route for performing the edit/update operation
  "/customer/update/:id": {
    controller: "CustomerController",
    action: "updatecustomer"
  }
};

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.