Quantcast
Channel: Dev Notes » Mac OS X
Viewing all articles
Browse latest Browse all 3

A Sample App with Node.js, Express and MongoDB – Part 2

$
0
0

In my last post, we created a simple Employee database using Node, Express and MongoDB. In this tutorial, we’ll add the ability to edit and delete employees.

Edit an Employee

The first thing we need to do is add additional functions to employeeprovider.js.

employeeprovider.js

//find an employee by ID
EmployeeProvider.prototype.findById = function(id, callback) {
    this.getCollection(function(error, employee_collection) {
      if( error ) callback(error)
      else {
        employee_collection.findOne({_id: employee_collection.db.bson_serializer.ObjectID.createFromHexString(id)}, function(error, result) {
          if( error ) callback(error)
          else callback(null, result)
        });
      }
    });
};

// update an employee
EmployeeProvider.prototype.update = function(employeeId, employees, callback) {
    this.getCollection(function(error, employee_collection) {
      if( error ) callback(error);
      else {
        employee_collection.update(
					{_id: employee_collection.db.bson_serializer.ObjectID.createFromHexString(employeeId)},
					employees,
					function(error, employees) {
						if(error) callback(error);
						else callback(null, employees)       
					});
      }
    });
};

The function findById will be used to retrieve employee data from our database based on ID. You’ll see this put into use when we edit our index view with an Edit button. The function update does exactly what it says, it updates the employee data in our database. Next we’ll add new routes to app.js.

app.js

//update an employee
app.get('/employee/:id/edit', function(req, res) {
	employeeProvider.findById(req.param('_id'), function(error, employee) {
		res.render('employee_edit',
		{ 
			employee: employee
		});
	});
});

//save updated employee
app.post('/employee/:id/edit', function(req, res) {
	employeeProvider.update(req.param('_id'),{
		title: req.param('title'),
		name: req.param('name')
	}, function(error, docs) {
		res.redirect('/')
	});
});

Again, the link we will add to our index view will use the get method. As you can see, it receives an _id parameter and calls the findById function we just created in employee provider.js. Later, we’ll create the employee_edit view to display the edit form. The post method calls the update function and redirects the user back to the index view.

employee_edit.jade

extends layout

block content
    h1= "Edit Employee"
    div.newemployee
        form( method="post")
            input(name="_id", type="hidden", value=employee._id.toHexString()) 
            div
                div
                    span.label Title :
                    input(type="text", name="title", id="editEmployeeTitle", value=[title])
                div
                    span.label Name :
                    input(type="text", name="name", id="editEmployeeName", value=employee.name)
                div#editEmployeeSubmit
                    input(type="submit", value="Update")
        a(href="/")!= "Back to Employee List"

index.jade

extends layout

block content
    h1= title
    #employees
        - each employee in employees
          div.employee
            div.created_at= employee.created_at
            div.title= employee.title 
            div.name= employee.name
                form( method="get", action="/employee/:id/edit") 
                    input(name="_id", type="hidden", value=employee._id.toHexString()) 
                    input(id="edit", value="Edit", type="submit")
        a(href="/employee/new")!= "Add New Employee"

We’ve added an Edit button to our index view that will call the get method we just created in app.js. The get method will then render the employee_edit view and the form post will update the employee. That is the bare bones minimum needed to update an employee in MongoDB.

Delete an Employee

Next, we’ll writes the methods necessary needed to delete an employee from MongoDB.

employeeprovider.js

//delete employee
EmployeeProvider.prototype.delete = function(employeeId, callback) {
	this.getCollection(function(error, employee_collection) {
		if(error) callback(error);
		else {
			employee_collection.remove(
				{_id: employee_collection.db.bson_serializer.ObjectID.createFromHexString(employeeId)},
				function(error, employee){
					if(error) callback(error);
					else callback(null, employee)
				});
			}
	});
};

The delete function will accept an employeeId parameter and delete the employee from our employee collection.

app.js

//delete an employee
app.post('/employee/:id/delete', function(req, res) {
	employeeProvider.delete(req.param('_id'), function(error, docs) {
		res.redirect('/')
	});
});

We’ve added an delete route that will call the delete function we just created in employeeprovider.js. Now we can add a Delete button to our index view.

index.jade

extends layout

block content
    h1= title
    #employees
        - each employee in employees
          div.employee
            div.created_at= employee.created_at
            div.title= employee.title 
            div.name= employee.name
                form( method="post", action="/employee/:id/delete") 
                    input(name="_id", type="hidden", value=employee._id.toHexString()) 
                    input(id="delete", value="X", type="submit")
                form( method="get", action="/employee/:id/edit") 
                    input(name="_id", type="hidden", value=employee._id.toHexString()) 
                    input(id="edit", value="Edit", type="submit")
        a(href="/employee/new")!= "Add New Employee"

Clicking the “X” button will call the delete route and delete the selected employee from our employee collection. I left out the additional changes made to style.styl for employee_edit.jade but you should be able to retrieve them from the source code link below.

You can now re-run your application and navigate to localhost:3000.

node app.js

This is the conclusion of our Employee database CRUD application. You should now have a basic knowledge of how to utilize the Express module for Node.js along with how to create and utilize a collection in MongoDB. Leave any questions you may have in the comment section below. I’ve posted the source code on github so feel free to use and modify it however you want.

Source Code: https://github.com/ijason/NodeJS-Sample-App

NodeJSpt2SS1
NodeJSpt2SS2


Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images