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
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
  1. DZone
  2. Coding
  3. JavaScript
  4. Getting Started With Node.js, Express, and Mongoose

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.

Kevin Hooke user avatar by
Kevin Hooke
·
May. 26, 16 · Tutorial
Like (3)
Save
Tweet
Share
15.57K Views

Join the DZone community and get the full member experience.

Join For Free

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);
Express Node.js Mongoose (web server)

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 2023 Software Testing Trends: A Look Ahead at the Industry's Future
  • Why Open Source Is Much More Than Just a Free Tier
  • Why You Should Automate Code Reviews
  • Top Five Tools for AI-based Test Automation

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
  • +1 (919) 678-0300

Let's be friends: