Node.js: Getting started with Express.js and MongoDB

08 / Feb / 2013 by Suroor Wijdan 1 comments

In my previous post, I explained how to get started with node.js and executing your first script with node. Now in this tutorial, we will go a step ahead and learn using Expressjs and MongoDB.

For people who are new, Express is a web application framework for node which provides a set of features that can be used to build single-page as well as multi-page web apps using MongoDB, which is a high-performance non-relational database. You can know more about both of these on their respective websites.

Installation Part:

Run this command to install the express module globally for developing apps.

[shell]$ npm install -g express[/shell]

Now go into your project directory and run the following commands in series:

[shell]$ express –sessions –css stylus –ejs myapp //creating app with express
$ cd myapp && npm install //installing dependencies[/shell]

Now you are done with initializing your first express app, we will come back to it later on. We now move to MongoDB, visit their website and download the installation .deb file for Linux systems or you can run the following command in

The next step is to move to MongoDB, visit their website and download the installation .deb file for Linux systems or you can run the following command in console:

[shell]sudo apt-get install mongodb-10gen[/shell]

After the installation is done, enter mongo in console and it should put you in the mongo console where you can execute various commands. Next, we install a node module named mongoose, it is a good MongoDB object modeling module for node.js so we will be using this. Now go to your myapp directory and run the following command in console:

[shell]$ npm install mongoose[/shell]

That ends the installation part, moving on to coding we need to first create views, which are basicalHTMLtml pages coded in .ejs (embedded javascript) format. If you goto the views directory in the app, you will find a default index.ejs file which we will be editing for our use later on. The basic thing we will be doing in this app is to save records in the database through a form and display it on the front end in another view.

For all DB processing create a new db.js file in a new model folder, this is where all our DB specific methods would be defined.

[js] var mongoose = require(‘mongoose’);
var demoSchema = new mongoose.Schema({
name:String
});
var hello = mongoose.model(‘hello’, demoSchema);
mongoose.connect(‘localhost’, ‘test’);[/js]

In the same file, make two new functions as follows:

[js]
exports.saveUser = function (req, res) {
this.user = req.body.user;
new hello({name:this.user}).save(function (err, login) {
if (err) {
return console.log(‘error’);
}
else {
console.log(‘Saved’);
res.render(‘index’, {title:’Welcome’, message:’User Added!’});
}
});
}
[/js]

[js]
exports.showUser = function (req, res) {
hello.find({},function (err, results) {
res.render(‘showUser’, { ‘title’:’Results’, ‘results’:results, message:” });
});
};
[/js]

Add the following lines to your app.js file:

[js]var db = require(‘./model/db’);
app.post(‘/saveUser’, db.saveUser);
app.get(‘/showuser’, db.showUser);[/js]

Now open the index.js file which will be in the routes directory of your project and replace its content with following code:

[js]exports.index = function(req, res){
<code>res.render(</code><code>’index'</code><code>, {title:</code><code>’Welcome to my App'</code><code>, message:</code><code>”</code><code>});</code>
};[/js]

Now open the index.ejs file and add the following content, (you can replace all of the previous content or just add to it).

[html]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><%= title %></title>
<meta name="description" content="First Express App- by Suroor Wijdan">
<link href="/stylesheets/style.css" rel="stylesheet">
</style>
</head>
<body>
<div>
<%=message%>

<form action="saveUser" method="POST">
<input type = "text" name = "user" >
<input type = "submit" value = "Save User">
</form>
</body>
</html>
[/html]

Make another showUser.ejs file in views with following code:

[html]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><%= title %></title>
<meta name="description" content="First Express App- by Suroor Wijdan">
<link href="/stylesheets/style.css" rel="stylesheet">
</style>
</head>
<body>

<table class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th>Results</th>
</tr>
</thead>
<tbody>
<% results.forEach(function(element) { %>
<tr>
<td><%=element.name%></td>
</tr>
<% }) %>
</tbody>
</table>
</body>
</html>
[/html]

We are done with creating our first express app, you can access the showUser page at your localhost:3000/showUser. Let me know if you have any queries related to this tutorial in comments below.

FOUND THIS USEFUL? SHARE IT

comments (1 “Node.js: Getting started with Express.js and MongoDB”)

Leave a Reply to venkatesh Cancel reply

Your email address will not be published. Required fields are marked *