Node.js Mongodb: Express, Mongoose Installation, Examples

Node.js Mongodb: Express, Mongoose Installation, Examples

    2 8534
    nodejs mongodb tutorial

    In this tutorial you will learn step-by-step how to

    • Install express, mongoose modules
    • Interact with mongodb

    External modules required: express, mongoose

    Express is a web application framework for node.js It provides low level services so that you can focus on more important things.
    Mongoose is a object modeling mapper for mongodb. Mongoose will help us smoothly interact with mongodb database server. You can also use mongodb module, but mongoose has additional benefits.

    Installing Mongodb

    • Download mongodb from
    • Now extract the file and save it in root(in windows its c:>) directory.
    • Create a folder named ‘data’ with a subfolder ‘db’ in it, this is where mongodb saves our databases, collections etc.
    • To start the mongodb server goto->terminal(cmd prompt)->enter the bin folder which is in your extracted folder->typein->mongod

    Note: make sure that your server is running while using node.js.
    For detailed installation and basic commands visit Install mongodb on mac, windows, linux

    In mongodb

    a table is called collection.
    a row is called document or record.
    a database is called as database.

    Installing the required modules

    • Install express module. Enter the terminal(cmd prompt)->npm install -g express (here -g is for global installation).
    • Once the installation is done create a project folder->goto->cmd prompt(terminal)->enter your project folder->typein->express. This will create a project structure->now you have to download the dependencies which are required by our project (ex:jade module). typein->npm install. this will download the dependant modules.
    • To install mongoose module->typein->npm install mongoose.
    • Once the installation is done you can start coding.

    Node.js mongodb example

    var express = require('express')
    , http = require('http')
    , mongoose = require('mongoose')
    , path = require('path');
    var app = express();
    // all environments
    app.set('port', process.env.PORT || 3001);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(express.static(path.join(__dirname, 'public')));

    app.get('/', function( req, res) {
    // connect to mongodb using mongoose
    var ArticleSchema = new mongoose.Schema({
    title: String,
    body: String
    var Articles = mongoose.model('Articles', ArticleSchema);
    // show list of articles
    app.get("/articles", function (req, res) {
    Articles.find({}, function (err, docs) {
    res.render('articles', {articles: docs});
    // Add a new Article
    app.get("/articles/new", function (req, res) {
    // Save the Newly created Article"/articles", function (req, res) {
    new Articles({
    title: req.body.title,
    body: req.body.body,
    }).save(function (err, user) {
    if (err) res.json(err);
    http.createServer(app).listen(app.get('port'), function(){
    console.log('Express server listening on port ' + app.get('port'));

    *copy and replace the above code in your app.js file.
    *goto->terminal(cmd prompt)->your project folder->run te app->node app.js
    *you can check the output in the browser at->localhost:3001

    Explanation of mongodb example

    • lines 1 to 4->here we have included all the required modules for our application.
    • lines 5 15->here express object is created and all these are default values provided by the express framework.
    • line 16->app.get(‘/’, function(req, res) { res.render(‘index’);}); ->when you open the browser and type localhost:3001/ this default path url(/) is taken by the framework and index.jade file is rendered. this index file is inside the views folder in your project. It will render the static content inside the index.jade file.
      We can also pass data into the index file using optional parameters, thats what happened at lines 29 and 35->whenever someone called localhost:3001/articles or localhost:3001/articles/new different pages are rendered. Now going back to
    • line 21->To connect to the server use mongoose.connect(‘mongodb://localhost/nodejsmongodb’);
      Here nodejsmongodb is the name of the database. you can use a different name. Note that a database will be created if it already doesn’t exist.
    • line 22-> Mongodb is schemaless database, but by using mongoose we can create a simple schema for better understanding.
    • line 26->Now a collection(table) named ‘articles’ is created using the above schema.
    • line 30-> We can interact with mongodb using article.find(),, article.update(), article.remove() methods available in mongoose.

    Its time to create the views for rendering the output

    By default express framework uses jade templating system.

    Inside views folder edit index.jade and replace with the following code

    extends layout

    block content
    p Welcome to nodejs mongodb tutorial
    a(href='/articles') Show All articles

    Create articles.jade file and paste the following code

    h1 Showing All Articles

    - each article in articles
    li article Title: #{article.title}
    li article Body: #{article.body}

    a(href="articles/new") Add New Article
    a(href="/") Home

    Note->If you want to pass dynamic values use #{variablename}

    Create new.jade file and copy the following code

    h1 Add new Article

    form(method="POST" , action="/articles")
    p Title:
    input#title(type="text" , name="title")
    p Body:
    input#body(type="textarea" , name="body")

    p: button(type="submit") Add New Article

    Thats it. You can go to home page at localhost:3001, add new articles at localhost:3001/articles/new and view all the articles at localhost:3001/articles

    1. Make Sure that mongodb (ur mongodb folder/bin>mongod) server is running while performing the above CRUD database operations.
    2. It is quite easy to learn jade templating system, but be careful while using node.js functions inside the .jade files. you need to use ‘-‘ like in articles.jade file.
    3. Whenever we modify our files don’t forget to restart the webserver.Use ctrl c to terminate and then run again.


    best node.js cms and blogging platforms

    1 7299
    docpad cms (nodejs) tutorial

    1 7139