How to CRUD MongoDB using NodeJS and SailsJS Part 4

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

Introduction

Welcome to Part 4 of the multiple-series tutorial, “How to CRUD MongoDB using NodeJS and SailsJS.” In Part 3, you learned how to do a controller configuration for your SailsJs application, and then display your data with a view. Today, you’ll practice how to delete a MongoDB document, as “Delete” is a part of CRUD operations. Let’s begin to discover how to configure the controller for completing the deletion process now.

If you know the steps and would like to bypass the specifics of this tutorial, skip to Just the Code.

Prerequisites

  • Read and practice Parts 1, 2 and 3 of the multiple-series tutorial, “How to CRUD MongoDB using NodeJS and SailsJS.”

Use SailsJS to delete a document inside a MongoDB Collection

The controllers must be configured first in order to carry out the document deletion process for the CRUD in MongoDB using NodeJs and SailsJs.

Configure The Controllers

  • Open CustomerController and modify it by adding the deletecustomer code :
1
2
3
4
5
6
7
8
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');
});
}

The method .destroy() is used to delete the record. When it finishes, it does a route-redirect to /customer/list.

  • Now, establish an action that updates the route.js like this:
1
2
3
4
'/customer/delete/:id': {
controller: 'CustomerController',
action: 'deletecustomer'
},

The chosen document for deletion contains an ID. It is known by the :paramName shown in the URL path.

Notice too that the code scans the CustomerController looking for deletecustomer for the action function. The action states what will be executed. In this example, it’s deletecustomer.

Include behavior methods for the configurations

The EJS list file needs configuration triggers, so you’ll need to update the list file.

  • Modify the list.ejs by including a Delete button so that the route for /customer/delete has the chosen document ID forwarded to it.
1
2
3
4
5
6
7
# Customer Information Listing **ID** **First Name** **Last Name** **Age** <%=
customer.id %> <%= customer.firstname %> <%= customer.lastname %> <%=
customer.age %>

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

The code shown above indicates that there’s a new column for the table created earlier for the CRUD in MongoDB using NodeJs and SailsJs delete operation example. Verify that you’ve done this. The column must have a form there. Do this first, and then put an action for the /customer/delete route to pass the customer ID that you want to delete. Use the Post method for the form.

  • Go to a browser and input the http://localhost:1337/customer/list URL to test it.

NOTE: You’ll need a test MongoDB document from a collection to delete. If you haven’t made one already, do so now.

  • Press the new button named “Delete” that you created earlier when you changed the list.ejs file. Since you made a test document for the purpose of testing CRUD MongoDB using NodeJs and SailsJs, you’re going to be deleting the document. The document represents the record you’re deleting in this example.

  • The result should look something like this :

3cb67b43483857ce1e0c339da9c1dd80.gif

Conclusion

This concludes Part 4 of “How to CRUD MongoDB using NodeJs and SailsJs.” In this segment, you learned how to perform a document deletion. The steps showed you how to do a controller configuration, route-redirect, and delete the document based on its ID in a MongoDB collection. Great job on finishing Part 4 of this multiple-series. Take some time to review Parts 1, 2, 3, and this lesson, and then proceed to Part 5 of “How to CRUD MongoDB using NodeJs and SailsJs.”

Just the Code

Here’s the entire code for performing a delete operation as illustrated in Part 4 of “How to CRUD MongoDB using NodeJS and SailsJS.” See the headers to go to specific areas of code.

Code for CustomerController

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
/**
 * 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({});
      // if (!customer) {
      // return response.notFound('Sails encountered an error in the database!');
      // }
      response.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;
  }
};

list.ejs modification steps

1
2
3
4
5
6
7
# Customer Information Listing **ID** **First Name** **Last Name** **Age** <%=
customer.id %> <%= customer.firstname %> <%= customer.lastname %> <%=
customer.age %>

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

Route.js for controller and action executions

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
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"
  }
};

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.