DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Design Patterns for Microservices: Ambassador, Anti-Corruption Layer, and Backends for Frontends
  • Five Java Books Beginners and Professionals Should Read
  • Auto-Scaling Kinesis Data Streams Applications on Kubernetes
  • Which Is Better for IoT: Azure RTOS or FreeRTOS?

Trending

  • Design Patterns for Microservices: Ambassador, Anti-Corruption Layer, and Backends for Frontends
  • Five Java Books Beginners and Professionals Should Read
  • Auto-Scaling Kinesis Data Streams Applications on Kubernetes
  • Which Is Better for IoT: Azure RTOS or FreeRTOS?
  1. DZone
  2. Coding
  3. JavaScript
  4. A simple Node.js web application that uses Mongoose, Express and MongoDB and returns JSON

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

Chad Lung user avatar by
Chad Lung
·
Jan. 04, 12 · Interview
Like (0)
Save
Tweet
Share
28.21K Views

Join the DZone community and get the full member experience.

Join For Free

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

JSON Express Web application Node.js MongoDB Mongoose (web server)

Opinions expressed by DZone contributors are their own.

Trending

  • Design Patterns for Microservices: Ambassador, Anti-Corruption Layer, and Backends for Frontends
  • Five Java Books Beginners and Professionals Should Read
  • Auto-Scaling Kinesis Data Streams Applications on Kubernetes
  • Which Is Better for IoT: Azure RTOS or FreeRTOS?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: