Getting Started with Mongoose and Node.js – A Sample Comments System

In this post, we’re going to be creating a sample comments system using Node, Express and Mongoose. Mongoose provides an object oriented interface for using MongoDB in Node. Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection. If you are not familiar with Mongoose I suggest you read the docs here.

Getting Started
For this tutorial, you will need Express and MongoDB installed on your machine. I covered this in a previous tutorial so refer to it in case you don’t already have them installed.

To install Mongoose, open your terminal screen and enter the following:

$ npm install mongoose

To automatically build out an application template for your application, navigate to the directory where you wish to create your application and run the following code:

mkdir MongooseExample
cd MongooseExample
express -c stylus
npm install -d

What this does:

  • create the directory for your application.
  • create your application template using the jade template engine and the stylus css engine.

You should now be able to run your application and see a generic Express application.

node app.js

Navigate to http://localhost:3000

Installing Dependencies
First we need to add our dependency for Mongoose. Open your package.json and add the following code:

  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app"
  "dependencies": {
    "express": "3.1.0",
    "jade": "*",
    "stylus": "*",
    "mongoose" : "3.2.0"

Everything should have already been there with the exception of "mongoose" : "3.2.0". Once you have saved the file run the following code to download and install the nodejs client for mongoose:

npm install -d

The Code
Now we’re going to create a file called db.js to configure MongoDB and our schema.

var mongoose = require( 'mongoose' );
var Schema   = mongoose.Schema;
var Comment = new Schema({
    username : String,
    content  : String,
    created  : Date
mongoose.model( 'Comment', Comment );
mongoose.connect( 'mongodb://localhost/express-comment' );

Save this file in the same directory as app.js. The first thing we do is include mongoose and get a reference to schema. Everything in mongoose is derived from a schema. Next, we create our Comment schema and compile it into a model. Last we open a connection to our express-comment database on our locally running instance of MongoDB.

Open app.js and add require( './db' ); at the top of the file. It should look this:

 * Module dependencies.
require( './db' ); //for mongoose. Require this first!!!

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(require('stylus').middleware(__dirname + '/public'));
  app.use(express.static(path.join(__dirname, 'public')));

app.configure('development', function(){

app.get('/', routes.index);
app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));

Open index.js and add the following code:

var mongoose = require( 'mongoose' );
var Comment = mongoose.model( 'Comment' );

exports.index = function ( req, res ){
  Comment.find( function ( err, comments, count ){
    res.render( 'index', {
        title : 'Comment System with Mongoose and Node',
        comments : comments

exports.create = function ( req, res ){
  new Comment({
    username : req.body.username,
    content : req.body.comment,
    created :
  }).save( function( err, comment, count ){
    res.redirect( '/' );

The first thing we do is require mongoose and the Comment model before we can use it. The index function is replaced with one that queries the database for comments and returns them to the index page. Comment.find is used to pull all comment collections. The create function saves a new comment from form values. We’ll create the form in a minute. First, add the following line to app.js: '/create', routes.create );
It should now look like this:

app.get('/', routes.index); '/create', routes.create );

Open index.jade and add the form and a loop to show the comments under the form.

extends layout

block content
  h1= title
        form( method="post", action="/create")
                    span.label Name :
                    input(type="text", class="nameTxt", name="username")
                    span.label Comment :
                    input(type="submit", value="Save")
    - each comment in comments
      div.comment comment.username
        div.created_at= comment.created
        div.content= comment.content 

You will need to pretty up the page so open style.styl and add the following code:

  padding: 50px
  font: 14px "Lucida Grande", Helvetica, Arial, sans-serif
  color: #00B7FF
    width 450px
  input[type =text]
    width 200px
    margin-left 38px
    width 200px
    margin-left 10px
  input[type =button], input[type =submit]
    clear both
    margin-left 85px
    display block
      text-align right !important
      display block
      float left
    float left
    float right
    clear both

Now re-run the application and you should be able to add comments which will display under the form. Navigate to localhost:3000 and make sure you have MongoDB up and running.

node app.js

Screen Shot

Download the source code at

For more information on storing data with Mongoose and Node I suggest you read MONGOOSE BASICS: STORING DATA WITH NODE.JS AND MONGODB


If possible can you attach and image of the final output? Also I am guessing threaded comments are not available here. Can you make a tutorial where you can reply to comments ?

Node.js plays a significant role in making JavaScript popular among the developers. The popularity of Node js development based on JavaScript engine can be credited to the efficiency and speed it provides to the development environment. The platform is easy to start, but as you move ahead the core functionalities of the app can become difficult. But with best practices and tips, you can make a huge difference between a launch disaster and a rock solid production app.

Leave a Reply

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

Please Do the Math      

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: