Hello World, Today we are going to discuss that how we can create dynamic website with nodejs and mongodb. Before starting this tutorial, I request you to read my previous article that how we can create simple static website with nodejs, express and jade. Because this article is extended version of my previous article.
I will use following technologies in this article.
- Nodejs
- Express
- Jade
- MongoDB
You can get the knowledge of nodejs, express and jade from my previous article. MongoDB is new for you.
I have divided the article in following parts:
- Introduction of MongoDB.
- Install and setup MongoDB.
- Connect MongoDB with our application.
- CRUD operation with Nodejs and MongoDB.
- Add Data
- Read Data
- Update Data
- Delete Data
Introduction of MongoDB
No one can explain better than Wikipedia. So According to Wikipedia:
MongoDB is a free open source cross-platform document-oriented database program. MongoDB is classified as a NoSQL database program, MongoDB used JSON like document with schemas.
Install and setup MongoDB
I am using window operating system, so here I have described installation according to my operating system. If you are using other operating system then you can read the installation docs from their official website.
- Download and install the setup from this link.
- Open your command prompt and go to the folder where you have installed the mongodb. Go to the bin folder and run the following command.
>mongod
The above command will be start mongodb server on 27017 port. See the screenshot:
If you are facing any error than please read their official installation doc from their official website.
Connect MongoDB in Our Application
Now we will connect mongodb with in our static website. Install mongodb dependency in our application with following npm command.
npm install mongodb –save
Also install mongoose with the following command.
npm install mongoose –save
The above commands will install the mongodb and mongoose in our application.
Here we are not directly interacting with MongoDB But we are using mongoose
- Open index.js file and add the replace the following code with previous code.
var path=require('path'); var express=require('express'); var bodyParser=require('body-parser'); var mongoose=require('mongoose'); var app=express(); // Database Connectivity mongoose.connect('mongodb://localhost:27017/sample-website'); mongoose.connection.on('open',function() { console.log('Mongoose connected.'); }); /* Data Rendering */ // Show the Index Page app.get('/',function(req,res){ res.render('index',{title:"Home Page",'description':'This is Home page description.'}); }); // Show the About Page app.get('/about',function(req,res){ res.render('index',{title:"About Page",'description':'This is About page description.'}); }); // Show the About Page app.get('/contact',function(req,res){ res.render('index',{title:"Contact Page",'description':'This is Contact page description.'}); }); // Set the view engine app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // Set Public Folder as static Path app.use(express.static(path.join(__dirname, 'public'))); // Run the Server app.listen('3000',function(){ console.log('Server is running at PORT '+3000); });
Please remember one thing that your mongo server should be running. If your mongo server is not running then run the server with “mongod” command.
After starting mongo server open another command prompt and go the project folder and run the following command.
node index.js
After running the above command you will see the following screenshot. This screenshot shows that mongoose is connected successfully.
We have successfully connected mongodb with mongoose in our application. Now we will perform the simple CRUD operation with mongodb, nodejs, express and Jade.
CRUD Operation
In this operation we will perform four simple task; create, read, update and delete. Before starting this crud tutorial i will introduce you to body-parser. This is the module that reposnible for submit the form data or read the form by server. In the above index.js file i have used this file. If you have not installed this dependency then install with the following npm command.
npm install body-parser --save
After installing body-parser, Add the following code before database connectivity.
// Form Data app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended:true}));
Read Data
- Update the index.jade file with crud link like following.
//- Index.jade html head title=title link(rel="stylesheet",href="/stylesheets/style.css",type="text/css") body div.container div.top-menu h1.page-heading=title ul li a(href='/') Home li a(href='/about') About li a(href='/contact') Contact li a(href='/crud') CRUD div.page-content p.page-description=description
- Replace the “/public/stylesheets/style.css” file code with the following
body{ font-family:Arial, Helvetica, sans-serif; } h1,ul{ margin: 0px; padding: 0px; } .container{ width:1000px; margin: 0 auto; height: auto; padding:10px; border:1px solid #ccc; box-shadow:0px 0px 5px #ccc; margin-top:5%; overflow: auto; } .top-menu{ border-bottom:1px solid #ddd; padding-bottom:5px; overflow: auto; margin-bottom: 30px; } .page-heading{ float: left; } .top-menu ul{ float: right; } .top-menu ul li{ list-style: none; display: inline-block; } .top-menu ul li a{ display: block; padding: 10px 5px; text-decoration: none; font-size: 13px; } /* Button STyling */ .button{ padding:5px; font-size: 13px; background: #ccc; margin: 5px; color: blue; }
- Create the tasks.jade file in views folder with following code.
//- tasks.jade html head title=title link(rel="stylesheet",href="/stylesheets/style.css",type="text/css") body div.container div.top-menu h1.page-heading=title ul li a(href='/') Home li a(href='/about') About li a(href='/contact') Contact li a(href='/crud') CRUD div.page-content p.page-description=description hr table(cellpadding=10,border="1",cellspacing="10") tr td(colspan="3",align="right") a(href='/crud/add',class="button") Add New tr th Title th Description th Action each task in taskList tr td=task.title td=task.description td a(href='/crud/edit/'+task._id,class="button") Edit a(href='/crud/delete/'+task._id,class="button") Delete
- Add the following code after database connectivity.
Schema=mongoose.Schema; // Creat Task Schema var Task=new Schema({ title:{type:String}, description:{type:String} }); var TaskModel=mongoose.model('Task',Task);
- Add the following code after above code.
// Read Data Start app.get('/crud',function(req,res){ TaskModel.find({},function(err,docs){ res.render('tasks',{'taskList':docs}); }); }); // Read Data End
Run the server and go to CRUD link, you will see the following screen shot.
Don’t worry about the above data because i have added while i was testing.
Add Data
- Create add-task.jade file in views folder with following code.
//- add-task.jade html head title=title link(rel="stylesheet",href="/stylesheets/style.css",type="text/css") body div.container div.top-menu h1.page-heading Add Task ul li a(href='/') Home li a(href='/about') About li a(href='/contact') Contact li a(href='/crud') CRUD div.page-content p.page-description We are adding task hr form(action='/crud/add',method='post') p=msg table(cellpadding="10",cellspacing="10") tr td label(for="title") Title td input(type="text",name="title") tr td label(for="title") Description td textarea(cols="22",name="description") tr td(colspan="2",align="right") input(type="submit")
- Now add the following code in index.js file after the read operation.
// Create Data Start app.get('/crud/add',function(req,res){ res.render('add-task'); }); // Add Task app.post('/crud/add',function(req,res){ if(req.body.title && req.body.description){ // Add Data var newTask=new TaskModel({ title:req.body.title, description:req.body.description }); var message='Data has been added'; newTask.save(function(err){ if(err){ var message='Data has not been added'; } }); // Show Message } res.render('add-task',{msg:message}); }); // Create Data End
When you run the server then you will the following add form for creating data.
When you add the data and go to the crud list page then you can see the added data.
So here we have successfully completed our create and read task. Now its turn to update and delete task.
Update Data
- Create the edit-task.jade file in views folder with the following code.
//- Index.jade html head title=title link(rel="stylesheet",href="/stylesheets/style.css",type="text/css") body div.container div.top-menu h1.page-heading Add Task ul li a(href='/') Home li a(href='/about') About li a(href='/contact') Contact li a(href='/crud') CRUD div.page-content p.page-description We are adding task hr form(action='/crud/edit/'+task._id,method='post') p=msg table(cellpadding="10",cellspacing="10") tr td label(for="title") Title td input(type="text",value=task.title,name="title") tr td label(for="title") Description td textarea(cols="22",name="description")=task.description tr td(colspan="2",align="right") input(type="submit",value="Update")
- Edit the index.js file and add the following code after add operation.
// Update Data Start app.get('/crud/edit/:id',function(req,res){ TaskModel.findOne({_id:req.params.id},function(err,docs){ res.render('edit-task',{'task':docs}); }); }); app.post('/crud/edit/:id',function(req,res){ // update Data var updateData={ title:req.body.title, description:req.body.description }; var message='Data has been not updated'; TaskModel.update({_id:req.params.id},updateData,function(err,numrows){ if(!err){ res.redirect('/crud/edit/'+req.params.id); } }); }); // Update Data End
Try the Update the data in the crud list.
Delete Data
- Add the following code after the update operation in index.js file.
// Delete Task app.get('/crud/delete/:id',function(req,res){ // Delete Data TaskModel.remove({_id:req.params.id},function(err){ if(!err){ res.redirect('/crud'); } }); }); // Delete Task ##End
Try to delete the data.
Thanks again for a great walkthrough. FYI, it looks like all the links to mongodb and Wikipedia point back to this article and not to the sites you intended
Thank you for the support. I have updated the link.