Technoon Tutorials
Node & MongoDB using Mongoose


Written by Rajesh V

Node.js, Express, EJS, Mongoose & MongoDB

This tutorial requires basic knowledge in Node.js & MongoDB. The 'mongoose' node module can be used to access the MongoDB from Node.js. Express is a web application framework for Node.js, which provides the easy way to build web applications with multi pages. Express comes with 'Jade', a templating engine. EJS is also a popular templating engine for Node.js. In this tutorial 'EJS' will be used as a templating engine.

Express & EJS

Install the 'express' & 'ejs' node modules using the below commands.

npm install express
npm install ejs

Let's see how to use the 'express' for handling the http requests. Use the 'require' method to import the express library to the node script. By passing the express object 'app' as an argument to the 'createServer' method, all the incoming http requests can be handled by the express framework. Save the below script as 'accessmongo.js' and run the script as 'node accessmongo.js'. Access the url 'http://localhost:3000' in the browser, Bingo ! Welcome to Technoons!

var express = require('express'),
http = require('http');
var app = express();

app.get('/', function(req, res) {
res.send('Welcome to Technoons!');
});

http.createServer(app).listen(3000, function() {
console.log("Server is listening on port 3000"); 
});

Configure the 'express' by setting the essential parameters. Take a note that 'ejs' is the view engine here.

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

Let's see how to display html elements using EJS. In the 'accessmongo.js' add the below code fragment. After this, create a file 'index.ejs' and include the below html fragments. The ejs file 'index.ejs' gets invoked when the request comes for the '/'. Note: All '.ejs' files has to be stored in the "views" folder as per the application configuration.

app.get('/', function(req,res) {
res.render('index.ejs');
});

<!DOCTYPE html>
<html>
<head>
<title>Mongo DB CRUD Operations </title>
</head>
<body>
<h2>CRUD operations using Node & Mongo DB </h2>
<a href="/add">Add a Product</ahref> <br>
<a href="/view/:id">View a Product</ahref> <br>
<a href="/viewall">View All Products</ahref> <br>
</body>
</html>

Run the 'accessmongo.js' and access the http://localhost:3000/, you will see the below page. You have learned to use the templating engine.



Accessing MongoDB from Node.js

For accessing the collections in the MongoDB the node module 'Mongoose' can be used. Install the Mongoose and include it in the 'accessmongo.js' as a required module.

npm install mongoose
mongoose = require('mongoose');

Mongoose module provides the easy access to MongoDB. MongoDB comes with a default database called 'test', for this example this 'test' database will be used. Collections in MongoDB are similar to 'Tables' in RDBMS and Mongo DB uses flexi schema approach. Connect to MongoDB 'test' database using the below script.

mongoose.connect('mongodb://localhost/test');

Create a MongoDB schema & a collection to store the product details using the below script. Create a reference to the 'product' object which uniquely represents a record in the collection. When this code gets executed, MongoDB creates a collection named "Products'.

var productSchema = new mongoose.Schema({
  prdId: String,
  name: { type: String }, 
  price: Number
})

var Product = mongoose.model('Product', productSchema);

Inserting records

First a html 'form' has to be created to capture the product details. Let's create a simple html form. EJS will be used to define the html form elements. Save this file as 'addProducts.ejs' and under the 'views' folder. Note: The submit button invokes a 'post' call.

<!DOCTYPE html>
<html>
<head>
<title>Add Product</title>
</head>
<body>
<h2>Enter Product Details </h2>
<form action="/new" method="POST">
  <p>
  <label for="ProductId">Product Id     : 
    </label><input type="text" name="ProductId"/> <br>
  <label for="ProductName">Product Name   : 
    </label><input type="text" name="ProductName"/> <br>
  <label for="ProductPrice">Product Price : 
    </label><input type="number" name="ProductPrice"/> <br>
  <input type="submit"/>
  </p>
</form>
</body>


In the accessmongo.js include the below code snippet. When the url comes with operation as 'add' then the view 'addProduct.ejs' gets invoked. The submit button click invokes the '/new' post. Using save() method in Mongoose module, the product details are persisted in MongoDB.

app.get('/add', function(req,res) {
    res.render('addProduct.ejs');
});

app.post('/new', function(req, res){
  new Product({
    prdId : req.body.ProductId,
    name  : req.body.ProductName,
    price   : req.body.ProductPrice
  }).save(function(err, prd){
    if(err) res.json(err);
    else    res.send("Product Successfully Added !");
  });
});

Invoke the URL 'http://localhost:3000/add' and submit the form. Congratulations !!! You have now learnt how to insert a record into MongoDB collection.


Viewing all the records

JSON is used to send & receive data to MongoDB. Now, create a 'display.ejs' in the "views" folder with the following html code.

<html>
<head>
<title>Data from Mongo DB</title>
</head>
<body>
<h2><%=message%></h2>

<% if( Array.isArray(products) ) { %>
<ul>
<%products.forEach( function( prd ){ %>
<b>
<li> <%= prd.prdId %> ; <%= prd.name %> ; $<%= prd.price %></li>
</b>
<% })} else { %>
<b>
Id: <%= products.prdId %>
Name: <%= products.name %>
Price: $<%= products.price %>
</b>
<% }; %>
</html>
</body>

Add the below script to the accessmongo.js. Function 'renderResult' is a helper function created to re-use the page rendering code.


app.get('/viewall', function(req,res) {
    Product.find({}, function(err, prds) {
    console.log("\nProducts !");
    console.log(prds); 
    renderResult(res, prds, "Product List from MongoDB :");
});});

function renderResult(res, prds, msg) {
  res.render('display.ejs', {message:msg, products:prds},
    function(err, result) {
      if (!err) {res.end(result);}
      else {res.end('Oops ! An error occurred.');
        console.log(err);}
});}

Invoke the URL http://localhost:3000/viewall. All the records in the "Products" collection in MongoDB will be displayed in this page.


Try yourself : Retrieve a record from MongoDB with a condition and display. e.g. find a product with id 'prd5555'.

Happy Coding !