Programming Tutorials

  • View all tutorials
  • More collection methods in MongoDB
    In this tutorial we'll be building off the previous tutorial where we installed MongoDB and setup a few basic routes with some collection methods. We'll be adding some more methods in this tutorial to provide more functionality for our application.

    Listing Users

    In the previous tutorial this is how our /list route ended up looking:
    app.get('/list', function (res, res) {
      var collection = db.collection('users');
      collection.find({}).toArray(function(err, result) {
        console.log(result);
        res.render('index');
      });
    });
    
    We'll modify this code to properly display the actual users on a web page instead of the console. First we'll create a new file in the views directory called list.ejs and we'll place the following code within it:
    <!DOCTYPE html>  
    <html>  
    <head>
      <meta charset="utf-8">
      <title>User page</title>
    </head>
    <body>
      <h1>Users</h1>
      <ul>
        <% for (var i = 0; i < users.length; i++) { %>
        <li> <a href="/user/<%= users[i].name %>"><%= users[i].name %></a> </li>
        <% } %>
      </ul>
    </body>
    </html>  
    
    The code above will take an array of users, and loop through them and provide a link to their profiles. Now we can modify the /list route to the following code:
    app.get('/list', function (res, res) {
      var collection = db.collection('users');
      collection.find({}).toArray(function(err, result) {
        res.render('list', {users: result});
      });
    });
    
    Now you can go to http://localhost:3001/ and add users, and if you go to http://localhost:3001/list then you should see a list of users like below:

    Editing Users

    To edit a user's information, we'll need to create three things: 1) HTML page that allows editing of user information 2) GET route to display new HTML page 3) POST route to update information First, create a new file in the views directory called edit.ejs, and add the following code into it:
    <!DOCTYPE html>  
    <html>  
    <head>
      <meta charset="utf-8">
      <title>User page</title>
    </head>
    <body>
      <h1>Edit: <%= name %> </h1>
      <form action="/user/edit" method="post">
        <input type="hidden" name="name" id="name" value="<%= name %>">
        <input type="text" name="age" id="age" value="<%= info.age %>" placeholder="Age" required> <br>
        <input type="text" name="occup" id="occup" value="<%= info.occup %>" placeholder="Occupation" required> <br>
        <input type="text" name="hobby" id="hobby" value="<%= info.hobby %>" placeholder="Hobby" required> <br>
        <input type="submit" value="Update">
      </form>
    </body>
    </html>  
    
    Now to display this page create the following route:
    app.get('/user/:name/edit', function (req, res) {
      var user = req.params.name;
      var collection = db.collection('users');
      collection.find({'name': user}).toArray(function(err, result) {
        if (result.length > 0) {
          var found = result[0];
          res.render('edit', { name: found.name, info: found });
        } else {
          res.send('User does not exist...');
        }
      });
    });
    
    This route is almost identical to the /user/:name route except that we render a different template to edit a user's information. Now, if you go to the following URL, you should see the user's information within a form. http://localhost:3001/user/<NAME>/edit The most important part now, is to create a POST route that will update the user's document in the Mongo collection. The code below uses the updateOne method to find a document, and then update its properties which are given as the second parameter:
    app.post('/user/edit', function (req, res) {
      var collection = db.collection('users');
      collection.updateOne(
        {'name': req.body.name}, 
        {$set: {
          age: req.body.age,
          occup: req.body.occup,
          hobby: req.body.hobby
        }}, function(err, result) {
          res.redirect('/user/' + req.body.name);
        });
    });
    
    You can now edit a user's information, and the changes will immediately be reflected on their profiles.

    Deleting Users

    We'll modify our edit.ejs file to include another form that will contain a delete button:
    <!DOCTYPE html>  
    <html>  
    <head>
      <meta charset="utf-8">
      <title>User page</title>
    </head>
    <body>
      <h1>Edit: <%= name %> </h1>
      <form action="/user/edit" method="post">
        <input type="hidden" name="name" id="name" value="<%= name %>">
        <input type="text" name="age" id="age" value="<%= info.age %>" placeholder="Age" required> <br>
        <input type="text" name="occup" id="occup" value="<%= info.occup %>" placeholder="Occupation" required> <br>
        <input type="text" name="hobby" id="hobby" value="<%= info.hobby %>" placeholder="Hobby" required> <br>
        <input type="submit" value="Update">
      </form>
      <br><br><br>
      <form action="/user/delete" method="post">
        <input type="hidden" name="name" id="name" value="<%= name %>">
        <input type="submit" value="Delete User" style="background:red;color:white;">
      </form>
    </body>
    </html>  
    
    We need to create a POST route now to actually remove the document from our collection. To accomplish this, we'll be using the deleteOne method which removes a document matching some query, in our case, deleting the document matching the name:
    app.post('/user/delete', function (req, res) {
      var collection = db.collection('users');
      collection.deleteOne({'name': req.body.name}, function(err, result) {
        res.redirect('/list');
      });
    });
    
    You can see now that when you click on the delete button, the user is immediately deleted and you are taken the the list of users page.

    Conclusion

    For more information on MongoDB methods, check out the resources below: Official MongoDB Quick Start Guide Collection API: e.g. find(), insertOne(), etc. Connecting and Working with MongoDB with Node & Express Node.js body parser module
    mrdaniel wrote this tutorial on 7/14/16 | javascript, nodejs, nosql, mongodb
    Comments
    Log in to submit a comment.