A simple Node.js web application that uses Mongoose, Express and MongoDB and returns JSON
Join the DZone community and get the full member experience.
Join For FreeToday 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.
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