Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Getting Started With Node.js, Express, and Mongoose

DZone's Guide to

Getting Started With Node.js, Express, and Mongoose

Recently, I set up a REST-based backend using Node.js, Express, and MongoDB for the first time in less than an hour, only to realize that I could've done it even quicker using npm. Read on and see how it's done.

· Web Dev Zone
Free Resource

Get deep insight into Node.js applications with real-time metrics, CPU profiling, and heap snapshots with N|Solid from NodeSource. Learn more.

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 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 were 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:

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);

Node.js application metrics sent directly to any statsd-compliant system. Get N|Solid

Topics:
node.js ,express ,mongoose ,backend ,npm ,rest

Published at DZone with permission of Kevin Hooke, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}