A Sample App with Node.js, Express and MongoDB – Part 1

In this post, we’re going to be creating a simple Employee database using Node, Express and MongoDB. By the end of this tutorial, you should be able to save a new employee and display all saved employees.

Getting Started
MongoDB
Installation and configuration of MongoDB is beyond the scope of this post. You can download MongoDB from their downloads page. For configuration and help getting Mongo started I’d suggest you read this tutorial. Again, this is assuming your using OS X. Make sure you have MongoDB up and running before you continue.

Express
Express is an incredible Node.js web application framework. It organizes your web app into an MVC architecture on the server side. To install Express, run the following code in Terminal:

// You may need to run this under sudo
npm install express -g

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 EmployeeDB
cd EmployeeDB
express -c stylus
npm install -d

What this does is:

  • 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

Creating our Employee Database
First thing we need to do is install a dependency on MongoDB, which will allow our application to access mongoDB. 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": "*",
    "mongodb": ">= 0.9.6-7"
  }
}

Everything should have already been there with the exception of "mongodb": ">= 0.9.6-7". Once you have saved the file run the following code to download and install the nodejs client for mongoDB:

npm install -d

Now we need to create our provider that will be capable to using MongoDB. Make sure this file is located in the same directory as app.js.

employeeprovider.js

var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;

EmployeeProvider = function(host, port) {
  this.db= new Db('node-mongo-employee', new Server(host, port, {safe: false}, {auto_reconnect: true}, {}));
  this.db.open(function(){});
};


EmployeeProvider.prototype.getCollection= function(callback) {
  this.db.collection('employees', function(error, employee_collection) {
    if( error ) callback(error);
    else callback(null, employee_collection);
  });
};

//find all employees
EmployeeProvider.prototype.findAll = function(callback) {
    this.getCollection(function(error, employee_collection) {
      if( error ) callback(error)
      else {
        employee_collection.find().toArray(function(error, results) {
          if( error ) callback(error)
          else callback(null, results)
        });
      }
    });
};

//save new employee
EmployeeProvider.prototype.save = function(employees, callback) {
    this.getCollection(function(error, employee_collection) {
      if( error ) callback(error)
      else {
        if( typeof(employees.length)=="undefined")
          employees = [employees];

        for( var i =0;i< employees.length;i++ ) {
          employee = employees[i];
          employee.created_at = new Date();
        }

        employee_collection.insert(employees, function() {
          callback(null, employees);
        });
      }
    });
};

exports.EmployeeProvider = EmployeeProvider;

As you can see, we declare all the necessary variables needed to access MongoDB. You’ll also see the getCollection method. A collection is a logical grouping of similar documents. MongoDB doesn’t have any tables; instead it contains collections. By calling collection on the db object, MongoDB will create the collection from scratch and return it. If the collection already exists it will simply return a reference to it. In our application, our collection will be called employees.
The findAll method returns all employees in the collection and the save method saves a new employee to our collection. Our employee datatype will look like this:

{
  _id: 0,
  title: '',
  name: '',
  created_at: new Date()
}

app.js
Open app.js, which should have been created by default, and add the following code:


/**
 * Module dependencies.
 */

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

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.set('view options', {layout: false});
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(require('stylus').middleware(__dirname + '/public'));
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

var employeeProvider= new EmployeeProvider('localhost', 27017);

//Routes

app.get('/', function(req, res){
  employeeProvider.findAll(function(error, emps){
      res.render('index', {
            title: 'Employees',
            employees:emps
        });
  });
});

app.get('/employee/new', function(req, res) {
    res.render('employee_new', {
        title: 'New Employee'
    });
});

//save new employee
app.post('/employee/new', function(req, res){
    employeeProvider.save({
        title: req.param('title'),
        name: req.param('name')
    }, function( error, docs) {
        res.redirect('/')
    });
});

app.listen(3000);

Most of the code should have already been created for you with the exception of the routes. The following line declares our EmployeeProvider which will access MongoDB:

EmployeeProvider = require('./employeeprovider').EmployeeProvider

The first route, '/', will retrieve all the employees from our employeeProvider and pass them to the index view. The second route, '/employee/new' will render the employee_new view which will display a form to the user. The last route will call the save method in our employeeProvider to save a new employee.

Views

Our views will be using the jade template engine. If you are not familiar with Jade I suggest you become familiar with it before moving on. Jade provides a syntax for declaring markup with a minimum of typed characters. It basically takes HTML, simplifies it and makes it readable. You can say goodbye to closing tags! Indentation/Spacing is very important in Jade. Indentation reflects nesting. The hierarchy of elements is expressed as indentation on the left hand-side. I spent hours trying to figure out why my Jade templates weren’t rendering only to find out my indentation was invalid. I’ll explain in a minute. First, lets create our Jade templates.

index.jade

extends layout

block content
    h1= title
    #employees
        - each employee in employees
          div.employee
            div.created_at= employee.created_at
            div.title= employee.title 
            div.name= employee.name
        a(href="/employee/new")!= "Add New Employee"

The first thing you’ll notice is extends layout and block content. The extends portion expresses what layout it belongs to similar to a master page in ASP.NET. The block portion declares what blocks it extends, which means a template can add markup to more than one part of the layout. Lets look at the layout:

layout.jade

doctype 5
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    block content

The block in index.jade must be the parent of everything within it meaning it must be at the far left of your document. Everything within it must be indented. This was the error I had when my jade templates weren’t loading. Like I said before, indentation is very important in Jade.

employee_new.jade

extends layout

block content
    h1= title
    div.newemployee
        form( method="post")
            div
                div
                    span.label Title :
                    input(type="text", name="title", id="editEmployeeTitle")
                div
                    span.label Name :
                    input(type="text", name="name", id="editEmployeeName")
                div#editEmployeeSubmit
                    input(type="submit", value="Save")
        a(href="/")!= "Back to Employee List"

Stylesheets

The default stylesheet has already been populated for us in `public/styesheets/style.styl’. The stylesheet uses the stylus css engine. Stylus is to CSS as Jade is to HTML.

body
  padding: 50px
  font: 14px "Lucida Grande", Helvetica, Arial, sans-serif
  font-size 13px
  text-align center
  text-stroke 1px rgba(255, 255, 255, 0.1)
  color #555
a
  color: #00B7FF
h1, h2
  margin 0
  font-size 22px
  color #343434
h1
  text-shadow 1px 2px 2px #ddd
  font-size 60px
#employees
  text-align left
  margin-left auto
  margin-right auto
  width 320px
  .employee
    margin 20px
    .created_at
        display none
    .title
        font-weight bold
        background-color #eee
    .name
        background-color #ffa
.newemployee
    border 3px
    border-color #000
    border-style dotted
    width 450px
    margin-left auto
    margin-right auto
    padding 14px
  input[type =text]
    width 200px
    margin-left 16px
    float left
  input[type =button], input[type =submit]
    clear both
    text-align left
    margin-left 165px
    display block
  .label
      width 150px
      text-align right !important
      display block
      float left

You can now re-run your application and navigate to localhost:3000. Make sure you have MongoDB up and running. For help running MongoDB, please refer to this tutorial.

node app.js

NodeJS1 2013-03-27 at 9.50.43 PM
NodeJS2 2013-03-27 at 9.51.48 PM
NodeJS3 2013-03-27 at 9.52.18 PM
NodeJS4 2013-03-27 at 9.53.33 PM

In my next post, part 2, we’ll add the ability to edit and delete employees. I’ll also be posting the source code in part 2. Stay tuned.



78 thoughts on “A Sample App with Node.js, Express and MongoDB – Part 1

  1. Pingback: A Sample App with Node.js, Express and MongoDB – Part 2 | Dev Notes

  2. Nice but I get an ugly message when I connect to my db.
    ========================================================================================
    = Please ensure that you set the default write concern for the database by setting =
    = one of the options =
    = =
    = w: (value of > -1 or the string ‘majority’), where < 1 means =
    = no write acknowlegement =
    = journal: true/false, wait for flush to journal before acknowlegement =
    = fsync: true/false, wait for flush to file system before acknowlegement =
    = =
    = For backward compatibility safe is still supported and =
    = allows values of [true | false | {j:true} | {w:n, wtimeout:n} | {fsync:true}] =
    = the default value is false which means the driver receives does not =
    = return the information of the success/error of the insert/update/remove =
    = =
    = ex: new Db(new Server('localhost', 27017), {safe:false}) =
    = =
    = http://www.mongodb.org/display/DOCS/getLastError+Command =
    = =
    = The default of no acknowlegement will change in the very near future =
    = =
    = This message will disappear when the default safe is set on the driver Db =
    ========================================================================================

    so I changed the code to:

    EmployeeProvider = function(host, port) {
    var mongoClient = new MongoClient(new Server(host, port));
    mongoClient.open(function(err,mongoClient){
    this.db = mongoClient.db("node-mongo-employee");
    this.db.open(function(){})
    });
    //this.db= new Db('node-mongo-employee', new Server(host, port, {safe: true, auto_reconnect: true, w:1}));
    //this.db.open(function(){});
    };

    But now I get:

    Express
    500 TypeError: Cannot call method 'collection' of undefined
    at EmployeeProvider.getCollection (/home/kkuo/Code/nodemongo1/employeeprovider.js:19:11)
    at EmployeeProvider.findAll (/home/kkuo/Code/nodemongo1/employeeprovider.js:27:10)
    at app.get.res.render.title (/home/kkuo/Code/nodemongo1/app.js:37:20)
    at callbacks (/home/kkuo/Code/nodemongo1/node_modules/express/lib/router/index.js:161:37)
    at param (/home/kkuo/Code/nodemongo1/node_modules/express/lib/router/index.js:135:11)
    at pass (/home/kkuo/Code/nodemongo1/node_modules/express/lib/router/index.js:142:5)
    at Router._dispatch (/home/kkuo/Code/nodemongo1/node_modules/express/lib/router/index.js:170:5)
    at Object.router (/home/kkuo/Code/nodemongo1/node_modules/express/lib/router/index.js:33:10)
    at next (/home/kkuo/Code/nodemongo1/node_modules/express/node_modules/connect/lib/proto.js:190:15)
    at Object.methodOverride [as handle] (/home/kkuo/Code/nodemongo1/node_modules/express/node_modules/connect/lib/middleware/methodOverride.js:37:5)

    Which is this line:

    this.db.collection('employees'…)

    any thoughts?

    • The first message that you got before you made the change is a warning and not an error. The app should still be working with the warning.
      If you want to suppress the warning, try playing around with the options.

      This should do it:
      this.db= new Db('node-mongo-employee', new Server(host, port, {w: 1}));

  3. Hi,
    I tried using this tutorial but got this error when hitting localhost :
    Oops! Google Chrome could not connect to localhost:3000
    how can I check to see if there’s a problem?

      • Yes I was able to show the 3 posts without any styling applied to them. After that the code stopped working.

        • It sounds like your node server stopped running.
          Try adding console.log('Server Running...'); at the end of app.js.

          It should look like this:

          app.listen(3000);
          console.log('Server Running...');

          Then run node app.js again. If you see “Server Running” in your terminal then you should be able to navigate to localhost:3000 successfully.

          • So I did that, and I do get the log message that the server is running. but localhost is not working.

          • Maybe I misunderstood the tutorial, but I assume I have to create an actual folder structure called employee/new, is that correct? should there be any files under that structure?
            Another thing is in the tut you mentioned that a new employee datatype will look like
            {
            _id: 0,
            title: ”,
            name: ”,
            created_at: new Date()
            }

            Am I supposed to define this somewhere? or is this done automatically?

          • No you do not have to create a folder structure called employee/new. This is just the route that will render your employee_new view.
            For example localhost:3000/employee/new/

            I put the source up on github so you can take a look at the folder structure and compare what you have.
            https://github.com/ijason/NodeJS-Sample-App

            The data type for your MongoDB collection will get created automatically.

  4. I’m trying to follow this tutorial but im getting the following error:

    ar employeeProvider = new EmployeeProvider(‘localhost’, 27017);
    ^
    TypeError: undefined is not a function
    at Object. (/Users/Keva161/Documents/Web Dev/Webapps/Node/EmployeeDB/app.js:32:24)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:492:10)
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)

    • sorry..

      var employeeProvider = new EmployeeProvider(‘localhost’, 27017);
      ^
      TypeError: undefined is not a function
      at Object. (/Users/Keva161/Documents/Web Dev/Webapps/Node/EmployeeDB/app.js:32:24)
      at Module._compile (module.js:449:26)
      at Object.Module._extensions..js (module.js:467:10)
      at Module.load (module.js:356:32)
      at Function.Module._load (module.js:312:12)
      at Module.runMain (module.js:492:10)
      at process.startup.processNextTick.process._tickCallback (node.js:244:9)

      • Did you created your EmployeeProvider variable at the top of app.js?

        var express = require('express')
          , routes = require('./routes')
          , user = require('./routes/user')
          , http = require('http')
          , path = require('path')
          , EmployeeProvider = require('./employeeprovider').EmployeeProvider; //< -- EmployeeProvider

        Also, make sure the file, employeeprovider.js, is located in the root directory with app.js.

  5. so I just download the github project, and right of the box I get this error message when I hit localhost :
    500 TypeError: /NodeJS-Sample-App/EmployeeDB/views/index.jade:6 4| h1= title 5| #employees > 6| – each employee in employees 7| div.employee 8| div.created_at= employee.created_at 9| div.title= employee.title Cannot read property ‘length’ of undefined

    • Same error for me. The employee_collection is empty, but get the same error when I try to save a new employee.

    • This error is because the mongodb server is not running in the background. Run “mongod” in a terminal windoe before “node app.js”

      • I am getting the same error. I have verified Mongo is running. I have even stopped and restarted Mongo. The error I am getting is as follows:

        TypeError: /Users/coyle/NodePractice/EmployeeDB/views/index.jade:6
        4| h1= title
        5| #employees
        > 6| – each employee in employees
        7| div.employee
        8| div.created_at= employee.created_at
        9| div.title= employee.title

        Cannot read property ‘length’ of undefined
        at jade.debug.unshift.lineno (eval at (/Users/coyle/NodePractice/EmployeeDB/node_modules/jade/lib/jade.js:152:8), :44:31)
        at eval (eval at (/Users/coyle/NodePractice/EmployeeDB/node_modules/jade/lib/jade.js:152:8), :111:4)
        at /Users/coyle/NodePractice/EmployeeDB/node_modules/jade/lib/jade.js:153:35
        at Object.exports.render (/Users/coyle/NodePractice/EmployeeDB/node_modules/jade/lib/jade.js:197:10)
        at Object.exports.renderFile (/Users/coyle/NodePractice/EmployeeDB/node_modules/jade/lib/jade.js:233:18)
        at View.exports.renderFile [as engine] (/Users/coyle/NodePractice/EmployeeDB/node_modules/jade/lib/jade.js:218:21)
        at View.render (/Users/coyle/NodePractice/EmployeeDB/node_modules/express/lib/view.js:76:8)
        at Function.app.render (/Users/me/NodePractice/EmployeeDB/node_modules/express/lib/application.js:506:10)
        at ServerResponse.res.render (/Users/coyle/NodePractice/EmployeeDB/node_modules/express/lib/response.js:798:7)
        at /Users/coyle/NodePractice/EmployeeDB/app.js:42:13

        Any suggestions?

        • Hi, I’m having the same problem, and mongoDB is defenitively running. I also checked the mongod log, and it shows 5 connections as soon as I start node app.js…

          How did you guys solved this?

          • Not sure if this will help but I figured out mine.
            I had missed the line:
            var BSON = require(‘mongodb’).BSON;

        • I’m getting this same error as well, but using Express v4.2.0 and Jade v1.3.1. So far I’ve been unable to find whatever it is that’s causing it, but I’ve verified that I’m matching the sample code exactly (with the exception of the new routes and configuration changes needed for Express 4+).

          Using the git repo worked as is for me, but it’s using a Express v3.1.0 and Jade v0.28.2. I’d love to know what I might be missing.

  6. Hi,

    I look for your MVC tutorial. and i found your site. but where do the mvc separation for the model? you put all your route / controller in the app.js.
    what if i will have a large app.get and app.post in the app.js, should it be put in the controller side?
    how to do it ?

    • In this example, the EmployeeProvider would be your model. As for your controller, you can use index.js located in the routes folder or you can create your own controller.

  7. Great tutorial! Very helpful, thank you. A few minor comments:

    There is a small spelling error: “employerprovider.js” vs “employeeprovider.js”. Also, to make it easier, maybe write that this file should be located in the same directory as app.js.

    Finally, as Thomas writes above, maybe explicitly let people know, they need to start MongoDB before the EmployeeDB app by running “mongod” (e.g. in the EmployeeDB dir: “mongod –dbpath .”).

  8. Thanks for the tutorial!

    I know you mentioned that the datatype is created automatically, but how could you go about changing the datatype? Say, for example, that I wanted to create a datatype resembling a blog post, with a title, body and so on – is there a way to specify that?

  9. Pingback: MongoDb insert via Node.js Native Driver not inserting | BlogoSfera

  10. Pingback: A Sample App with Node.js, Express and MongoDB – Part 1 | Dev Notes | CupScript

  11. I got following errors when running “node app.js” can you help me ?

    G:\project\emp>node app.js

    module.js:340
    throw err;
    ^
    Error: Cannot find module ‘./routes/user’
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:362:17)
    at require (module.js:378:17)
    at Object. (G:\project\emp\app.js:7:12)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:492:10)

  12. I’m using Linux and I get the following error:

    module.js:333
    throw err;
    ^
    Error: Cannot find module ‘./routes’
    at Function.Module._resolveFilename (module.js:331:15)
    at Function.Module._load (module.js:273:25)
    at Module.require (module.js:357:17)
    at require (module.js:373:17)
    at Object. (/ProfilesDB/web.js:2:16)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:349:32)
    at Function.Module._load (module.js:305:12)
    at Function.Module.runMain (module.js:490:10)

    I wonder if anyone has any suggestions?

    • The issue is it can’t find your routes folder or anything in it. Usually this is created for you if you create your project with something like WebStorm. But if you are manually creating your project then it won’t be there.

      At the top of your app.js you can remove these lines and your app will work.
      , routes = require(‘./routes’)
      , user = require(‘./routes/user’)

  13. Pingback: Express.js | M's Web Dev

  14. Very nice tutorial!
    I had to edit one line in the EmployeeProvider to because MongoDB was giving some warning.
    EmployeeProvider = function(host, port) {
    this.db= new Db(‘node-mongo-employee’, new Server(host, port), {safe: false}, {auto_reconnect: true});
    this.db.open(function(){});
    };

  15. Sorry for asking this noob question, I am new to NodeJS. I am really really confused on how the syntax of node works.

    var Db = require(‘mongodb’).Db;

    Can you please explain why you have this code. Why does it need to have .Db after require(). is it necessary to do this? why is it in a form of “promise” and its assigned to it self? whats the logic behind this code? Enlighten me PLEASE!

  16. Pingback: Please explain this NodeJS Syntax [on hold] | BlogoSfera

  17. Pingback: A Sample App with Node.js, Express and MongoDB ...

  18. Pingback: LEAN and MEAN (Mongodb ExpressJS AngularJS NodeJS) on CloudBees, OpenShift, Heroku and AppFog (draft) « /dev

  19. Great tut! Successfully implemented on Windows 7 computer. Be sure to follow the special instructions for Windows 7 for MongoDB. I also noted that “npm install express -g” did not build the express framework in my project. Instead, I had to just run “npm install” and express installed correctly within my project folder.

  20. full of bad practices and general bad ideas.

    you’re releasing globals all over the place and never handling errors. this is not a good way to “start off” with node/express/mongodo.

  21. Thank you so much for this! I got everything up and running just fine ad described, however I can’t get Express to allow a HTTP Post for a new user outside the JADE form. So for example if I wanted to call my new REST service to add a new employee from Python the code below should do the trick, but it errors out with a 302 on the server.

    import httplib, urllib
    conn = httplib.HTTPConnection(“localhost:3000″);
    params = urllib.urlencode({‘title':’floor manager’,’name':’john williams’})
    conn.request(“POST”, “/employee/new”, params)
    content = conn.getresponse()
    print content.reason, content.status
    print content.read()
    conn.close()

  22. A bit new to mongo still. The sample code in this article works. If I kill the node server and restart it I see the employee records persisted…. However, if I go to a console and run mongo then execute db.employees.find() I see nothing. Furthermore, if I add new employees at the console (e.g. db.employees.save({title:’president’, name:’William Trace’}) then perform a find: db.employees.find() I can see William Trace but none of the employees added through the node/express form… So how do I direct the mongo console to the same repository node/express is using?

    • worked fine for me when I checked. Is mongodb set up correctly? did you set up a path in your ~/.zshrc or ~/.bachrc or how ever you set your system up?

  23. Very very nice tutorial, I just did copy and paste your code to my files the app runs chummingly, really great tutorial, I am using unbuntu 10.04 lts lucid lynx

  24. Dear Nice Work but assist me I did all as you mentioned but whem y start with localhost:3000 didnt appear the link add a new employee, Mongo is Up, Node app.js is up. Where is the problems, stylus was changed, and the route put properly . Thanks jm3

  25. This is my error on express. Plz help
    Express
    500 TypeError: Cannot call method ‘findAll’ of undefined
    at app.get.res.render.title (/Users/txshon/Dropbox/Google Drive/04)Practice/NodeJS/EmployeeDB/app.js:37:19)
    at callbacks (/Users/txshon/Dropbox/Google Drive/04)Practice/NodeJS/EmployeeDB/node_modules/express/lib/router/index.js:164:37)
    at param (/Users/txshon/Dropbox/Google Drive/04)Practice/NodeJS/EmployeeDB/node_modules/express/lib/router/index.js:138:11)
    at pass (/Users/txshon/Dropbox/Google Drive/04)Practice/NodeJS/EmployeeDB/node_modules/express/lib/router/index.js:145:5)
    at Router._dispatch (/Users/txshon/Dropbox/Google Drive/04)Practice/NodeJS/EmployeeDB/node_modules/express/lib/router/index.js:173:5)
    at Object.router (/Users/txshon/Dropbox/Google Drive/04)Practice/NodeJS/EmployeeDB/node_modules/express/lib/router/index.js:33:10)
    at next (/Users/txshon/Dropbox/Google Drive/04)Practice/NodeJS/EmployeeDB/node_modules/express/node_modules/connect/lib/proto.js:190:15)
    at Object.methodOverride [as handle] (/Users/txshon/Dropbox/Google Drive/04)Practice/NodeJS/EmployeeDB/node_modules/express/node_modules/connect/lib/middleware/methodOverride.js:49:5)
    at next (/Users/txshon/Dropbox/Google Drive/04)Practice/NodeJS/EmployeeDB/node_modules/express/node_modules/connect/lib/proto.js:190:15)
    at multipart (/Users/txshon/Dropbox/Google Drive/04)Practice/NodeJS/EmployeeDB/node_modules/express/node_modules/connect/lib/middleware/multipart.js:64:37)

  26. Hi ijason
    Can I use html instead of jade for creating the view?
    If so, I wanted to know why you did not use html5 instead of jade

  27. Good Job!!! It works nicely… But m facing a problem in edit section. When i click the edit option the info is retrieved from db n displayed but when i make changes n click the update button nothing happens… pl help…

  28. AWESOME example.
    But can u write the same pgm without using callbacks and prototypes?
    If it is possble then please post it.
    We r waiting for ur response.

  29. I am getting the same error and I have verified Mongo is running. I have even stopped and restarted Mongo.

    Any other suggestions on what could be causing this?

  30. EmployeeProvider = function(host, port) {
    this.db= new Db(‘node-mongo-employee’, new Server(host, port, {safe: false}, {auto_reconnect: true}, {}));
    this.db.open(function(){});
    };
    it seems open the db in the constructor is not the best practice. Becase it may export the db before it really opened.

  31. I was getting Express
    500 TypeError: D:\EmployeeDB\views\index.jade:6 4| h1= title 5| #employees > 6| – each employee in employees 7| div.employee 8| div.created_at= employee.created_at 9| div.title= employee.title Cannot read property ‘length’ of undefined
    so i fired
    C:\mongodb\bin\mongod.exe
    followed by node app.js
    Worked for me .

  32. I would like to try and find a working example of how I can make the same requests to mongodb thru node.js to get data into an ext.js grid. Is this possible?

  33. I am getting this error while clicking on “save” button
    500 TypeError: undefined is not a function
    at Db._executeInsertCommand (D:\sreevishnu\Employee with MEAN\EmployeeDb\node_modules\mongodb\lib\mongodb\db.js:1900:46)
    at insertAll (D:\sreevishnu\Employee with MEAN\EmployeeDb\node_modules\mongodb\lib\mongodb\collection\core.js:223:26)
    at Collection.insert (D:\sreevishnu\Employee with MEAN\EmployeeDb\node_modules\mongodb\lib\mongodb\collection\core.js:35:3)
    at D:\sreevishnu\Employee with MEAN\EmployeeDb\employeeprovider.js:46:29
    at D:\sreevishnu\Employee with MEAN\EmployeeDb\employeeprovider.js:16:10
    at Db.collection (D:\sreevishnu\Employee with MEAN\EmployeeDb\node_modules\mongodb\lib\mongodb\db.js:495:44)
    at EmployeeProvider.getCollection (D:\sreevishnu\Employee with MEAN\EmployeeDb\employeeprovider.js:14:11)
    at EmployeeProvider.save (D:\sreevishnu\Employee with MEAN\EmployeeDb\employeeprovider.js:35:10)
    at D:\sreevishnu\Employee with MEAN\EmployeeDb\app.js:53:22
    at callbacks (D:\sreevishnu\Employee with MEAN\EmployeeDb\node_modules\express\lib\router\index.js:161:37)

  34. Packages install (not sure which one is required):
    npm install express -g
    npm install stylus -g
    npm install express-generator -g
    ln -s /usr/bin/nodejs /usr/bin/node
    express -c stylus
    npm install -d
    + the routing mechanism has evolved:

    This line in the article app.js does not work
    app.use(app.router);

    In the generated app.js, comment:

    //app.use(‘/’, routes);
    //app.use(‘/users’, users);
    //app.use(app.router);

    // catch 404 and forward to error handler
    /*app.use(function(req, res, next) {
    var err = new Error(‘Not Found’);
    err.status = 404;
    next(err);
    });*/

    Fix
    app.get(‘/’, function(req, res) {
    with:
    app.route(‘/’).get(function(req, res) {

    And fix:
    app.get(‘/employee/new’, function(req, res) {
    with:
    app.post(‘/employee/new’, function(req, res){

    Now it works.

Leave a Reply

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

*

     

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>