Search Courses

Search Courses
Home / Blog
Simple shopping list on expressjs and mongodb:CRUD using mongoose

Simple shopping list on expressjs and mongodb:CRUD using mongoose

Posted on : 12,Apr 2014 2195

Simple CRUD application using expressjs and mongoDB from mongolab

My current project work tasked me to create a CRUD (Create, Read, Update and Delete) application on node.js. I looked at some blogs on the web for expressjs and MongoDB on cloud and couldn’t find one that worked perfectly for my situation so i mashed a few together and ended up with this- and I learn a few lessons on the way.

I am using expressjs framework and MongoDB(free database upto 1GB, I guess) on MongoLab. I have deleted functionality which are not required and came up with clean and coherent code to achieve all CRUD operation. I have not included any form validation for demo.I am avoiding all unnecessary installation, if you want to check out installation part of node.js , please read my previous blog from here .


What you will need to start coding is
  • node.js installed and up on your machine if you are working on local.
  • Account on mongolab , you can create a free one from mongolab
  • Install mongoose module on node
npm install mongoose

Let us check app.js code . code is well commented for better understanding.I am setting up a new mongoose model . You don't need to create a collection in database. Mongoose will take care of that part.Initialize a schema , that is table structure . For my shopping list there are two fields , item name and buying status. From people of relation database background collection is same as table and documents or objects are sames as rows.

var shoppingSchema = new mongoose.Schema({
itemname: { type: String }
, status: { type: String }
});
var Shop = mongoose.model('Shop', shoppingSchema);

Log In to MongoLab. It has created a collection called shops with no documents.



Let us look at CREATE code in app.js. Using mongoose model.save to insert a new document to collection. All success messages are rendered on message.jade.


app.post( '/create', 
function (req, res){
var shop = new Shop({
itemname: req.body.itemname
, status: 'Not Bought'
});
shop.save(function(err, use) {
if (err) return console.error(err);
res.render('message', {
message: 'New item added'
});
});
}
);

message.jade code looks like this


extends layout
block content
p
div.container
div.row
div.well
p
b #{message}

Check form jade , I have named it as create.jade from where the fields are captured.


form(name="additem",method="post",action="/create")
input(name='_csrf', type='hidden', value=csrfToken)
.well.well-sm
h3 Add item
div.form-group
label.col-sm-4 Item Name
div.col-sm-8
input.form-control(placeholder='Milk',
required=true,
name='itemname',
id='itemname'
type='text',
value=itemname)
div.form-group
label.col-sm-4
div.col-sm-8
br
button.login.btn.btn-primary.btn-md(type='submit') Create




New document is added to collection.






Adding a new document is done.Now let us try READ that row or document. app.js code for reading is as below. I am reading only items with status "Not Bought"


//read from database
app.get('/read' ,
function (req, res ){
var shop = new Shop({
itemname: req.body.itemname
, status: 'Not Bought'
});
Shop.find({'status':'Not Bought' },function(err, items) {
if (err) return console.error(err);
console.dir(shop);
res.render('read', {items:items});
});
}
);

While displaying the read documents, I am using two forms , one to update the status to bought and another to delete the document. Check the read.jade code snippet for displaying and having forms for update and delete.


 .panel-body
ul.list-group
each item in items
li.list-group-item
div.form-group
div.col-sm-4
span.label.label-success #{item.itemname}
div.col-sm-4
form(name="update",method="post",action="/update")
input(type="hidden", name="itemname",value=item.itemname)
button.btn-sm.btn.btn-primary.btn-md(type='submit')
small I bought it
div.col-sm-4
form(name="delete",method="post",action="/delete")
input(type="hidden", name="itemname",value=item.itemname)
button.btn-sm.btn.btn-danger.btn-md(type='submit')
small I don't need it





Now let us check the UPDATEpart of app.js. I am reading the item to be updated and its status is updated as "Bought". The below code finds the record with itemname and update it with new status


app.post( '/update',function (req, res ){
var query = {"itemname": req.body.itemname};
var update = {"status":"Bought"};
var options = { multi: true};
Shop.findOneAndUpdate(query, update, options, function(err, result) {
if (err) return console.error(err);
console.dir(result);
res.render('message', {
message: 'Item updated ' + result
});
});
});






Finally delete code snippet from app.js.The below code find the record with itemname and delete it from database.


app.post( '/delete',   
function (req, res ){
Shop.find({ itemname:req.body.itemname }).remove().exec(function callback (err, numAffected) {
if (err) return console.error(err);
console.dir(numAffected);
res.render('message', {
message: 'Item updated ' + numAffected
});
});
});


Hope this tutorial helps for a starter. Code for app.js and views are available here




Join the discussion

Improve the thread with your input and questions.
Carl Usmov
Consultant at IT Synergy Inc

Member Since : Dec, 2012

San Francisco California

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable networ

Take course on


Interested in node.js? We will notify you when knowledge is shared.