A simple Node.js web application that uses Mongoose, Express and MongoDB that returns JSON

Post to Twitter

Today I’m going to show you how to build a simple application that uses Nodejs, Mongoose, Express and MongoDB that will persist some data and get it back. It will also have a simple configuration file so I can configure my routes in Express. For those that don’t know, Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment and Express is a Sinatra inspired web development framework for node.js.


I’m installing and running this on Ubuntu 11.x. If your using OS X you might need to make some changes. With a clean Ubuntu 11.x I installed Node.js and NPM (Node Package Manager).

Installing Node (the current version as of the date of this article is v.0.6.6, use an apt package if you prefer or download it from the Nodejs website). Below are the instructions to build it from the source copied from GitHub:

$ sudo apt-get update
$ sudo apt-get install git-core curl build-essential openssl libssl-dev
$ mkdir nodejs && cd nodejs
$ git clone https://github.com/joyent/node.git && cd node
$ git checkout v0.6.6
$ ./configure
$ sudo make install
$ node -v

Update: Dec. 22, 2011 – It looks like NPM is now installed in newer builds of Node, if you have an older version that doesn’t include NPM you can install it like this:

$ curl http://npmjs.org/install.sh | sudo sh
$ npm -v

Now, install the packages we will need:

$ npm install mongoose
$ npm install express

Note: Please note that there is an express-mongoose plugin but I won’t be using it for this project.

Install MongoDB with the instructions found on their site. For Ubuntu it’s pretty easy.

Once MongoDB is installed and running your ready to write the code. There will be two files, one for the config and one for the app.

Note: There are JavaScript/Nodejs patterns and best practices you can follow, this code is meant to be simple and small in size. Adjust as you see fit.

Contents of config.js

var config = {};
config.routes = {};

config.routes.feed = '/user';

module.exports = config;

Contents of myapp.js

var express = require('express')
    app = express.createServer(),
    config = require(__dirname + '/config'),
    mongoose = require('mongoose'),
    db = mongoose.connect('mongodb://localhost/mydb'),
    Schema = mongoose.Schema;

var User = new Schema({
  username: String,
  title: String
});
var userModel = mongoose.model('User', User);

var user = new userModel();

user.username = 'Chad';
user.title = 'Senior Developer';
user.save(function(err) {
  if (err) throw err;
  console.log('User saved, starting server...');
  app.listen(8080);
});  

app.configure( function() {
    console.log('I will be listening on: ' + config.routes.feed);
});

app.get(config.routes.feed, function(req, res) {
    res.contentType('application/json');  
   
    userModel.findOne({'username': 'Chad'}, function(err, user) {
      if (user != null) {
        console.log('Found the User:' + user.username);
        res.JSON(user);
      }
    });
});

Run the code:

$ node myapp.js

Open a web browser and go to the following address: http://localhost:8080/user/

You should get back some JSON.

{"title":"Senior Developer","username":"Chad","id":"4eh21far10597eb52z000001"}

Theo code is pretty simple. We bring in the required libraries, declare the schema and ensure at least one entry is in MongoDB before starting the server. Also, you could very easily do this without Express since this is such a trivial example.

If your web browser refuses to open the content simply change this line of code:

res.contentType('application/json');

To:

res.contentType('text/plain');

– just remember to change this back if you do want to truly pass back JSON results to a target aware listener.

Post to Twitter

This entry was posted in MongoDB, Node.js, Open Source. Bookmark the permalink.

2 Responses to A simple Node.js web application that uses Mongoose, Express and MongoDB that returns JSON

  1. eeemsi says:

    o hai,
    this does sound very interesting… anyway i have one question – why do you install npm by hand? it is included into nodejs since v0.6.?5?

  2. Chad Lung says:

    @eeemsi,

    Yes I just realized that this morning when I was installing the new Node OS X package for version 0.6.6 and seen that NPM was bundled now. I’ll update the article.

    Thanks.

    Chad

Comments are closed.