Route examples — Mongoose/Express/Node.js

GET

Simple HTTP response

var express = require('express')
var app = express()

// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
  res.send('GET request to the homepage')
})

Search records and sort by date1

const express = require('express');
const router = express.Router();

// Record - Mongoose Schema
const Record = require('../../models/Record');

router.get('/', (req, res) => {
  Record.find()                       // search mongo db
    .sort({ date: -1 })               // sort in descending order
    .then(records => res.json(records))   // format response as json
});

module.exports = router;

POST

router.post('/', (req, res) => {
  const newRecord = new Record({     // creates a new Record but doesn't save to db
    name: req.body.name
  });
  newRecord.save().then(record => res.json(record)); // save to db and send as json
});

DELETE

router.delete('/:id', (req, res) => {
  Record.findById(req.params.id)
    .then(record => record.remove().then(() =>
                                         res.json({success: true}))) // if success
                                                                     // return true
    .catch(err => res.status(404).json({success: false})); // if error return false
});

See Also


  1. Adapted from https://github.com/bradtraversy/mern_shopping_list