NoSQL Zone is brought to you in partnership with:

I've been in the world of software development for 14+ years working with most mainstream programming languages at some point. Chad is a DZone MVB and is not an employee of DZone and has posted 38 posts at DZone. You can read more from them at their website. View Full User Profile

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

01.04.2012
| 23006 views |
  • submit to reddit

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) and NPM:

$ 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
$ 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('./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.send(JSON.stringify(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.

 

 

From http://www.giantflyingsaucer.com/blog/?p=3497

Published at DZone with permission of Chad Lung, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Kathy John replied on Thu, 2012/02/23 - 10:42am

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?

Enrique González replied on Wed, 2013/07/03 - 7:37am

Just I was looking for.


Thanks

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.