Getting started with node.js, Express and Mongoose

I started tinkering with some test data creation scripts using Node.js a while back, but it’s been on my todo list to dig deeper into some Node. I recently walked through this very good article, and got a REST based backend using Node.js, Express and a MongoDB up and running in less than an hour. Pretty good going for learning a new tech stack 🙂

After putting together the app from the steps in the article, I realized there was a few steps that could have been simplified. For example, instead of hand coding the package.json as in the article, you can let npm update it for you by passing the –save option. So, to create an initial package.json:

npm init

and walk through the prompts.

Next, instead of manually adding the dependencies for Express, Mongoose and body-parser, again, use npm to install and add them to the package.json file with –save:

npm install express --save

npm install mongoose --save

npm install body-parser --save

That saves some work – no need to edit the package.json file by hand when the tool maintains it for you. Without the –save option npm still downloads the dependency, but –save writes the details into your package.json as well.

Using Mongoose with Express certainly gets you up and running with basic CRUD using REST pretty quick and easy with minimal coding. I was surprised how little code it takes to get the basics implemented. I’ve shared my version of the completed app to GitHub for future reference here, and for quick reference below:

[code]

var express = require(‘express’);
var app = express(); //init Express
var bodyParser = require(‘body-parser’);
var mongoose = require(‘mongoose’);
var Contact = require(‘./app/models/Contact’);
mongoose.connect(‘mongodb://nodetest:yourpassword@localhost:27017/nodetest’);
//init bodyParser to extract properties from POST data
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;

//init Express Router
var router = express.Router();

//default/test route
router.get(‘/’, function(req, res) {
res.json({ message: ‘App is running!’ });
});

router.route(‘/contacts/:contact_id’)
// retrieve contact: GET http://localhost:8080/api/bears/:bear_id)
.get(function(req, res) {
Contact.findById(req.params.contact_id, function(err, contact) {
if (err)
res.send(err);
res.json(contact);
});
})
// update contact: PUT http://localhost:8080/api/contacts/{id}
.put(function(req, res) {
Contact.findById(req.params.contact_id, function(err, contact) {
if (err) {
res.send(err);
}
else {
contact.firstName = req.body.firstname;
contact.lastName = req.body.lastname;
contact.save(function(err) {
if (err)
res.send(err);

res.json({ message: ‘Contact updated!’ });
})
}
});
})
//delete a contact
.delete(function(req, res) {
Contact.remove({
_id: req.params.contact_id
}, function(err, contact) {
if (err)
res.send(err);

res.json({ message: ‘Successfully deleted contact’ });
});
});

router.route(‘/contacts’)
// create contact: POST http://localhost:8080/api/contacts
.post(function(req, res) {
var contact = new Contact();
contact.firstName = req.body.firstname;
contact.lastName = req.body.lastname;

contact.save(function(err) {
if (err)
res.send(err);

res.json({ message: ‘Contact created!’ });
});
})
//GET all contacts: http://localhost:8080/api/contacts
.get(function(req, res) {
Contact.find(function(err, contacts) {
if (err)
res.send(err);

res.json(contacts);
});
});

//associate router to url path
app.use(‘/api’, router);

//start the Express server
app.listen(port);
console.log(‘Listening on port ‘ + port);
[/code]

One Reply to “Getting started with node.js, Express and Mongoose”

Leave a Reply to Nick Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.