Skip to content

Instantly share code, notes, and snippets.

@nmajor
Created January 6, 2016 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmajor/91f4fd6788dce18b46ff to your computer and use it in GitHub Desktop.
Save nmajor/91f4fd6788dce18b46ff to your computer and use it in GitHub Desktop.
Complete REST Routes and Methods for an Express.js + Mongoose.js API
// controllers/models.js
var Model = require('../models/model');
var modelController = {
find: function(req, res, next) {
Model.where()
.then(function(models) {
res.json(models);
});
},
get: function(req, res, next) {
Model.findById(req.params.id)
.then(function(model) {
res.json(model);
});
},
create: function(req, res, next) {
new Model(req.body)
.save()
.then(function(model) {
res.json(model);
});
},
update: function() {
var conditions = {_id: req.params.id};
Model.findOneAndUpdate(conditions, req.body, {new: true})
.then(function(model, blah) {
res.json(model);
});
},
patch: function(req, res, next) {
var conditions = {_id: req.params.id};
Model.findOneAndUpdate(conditions, req.body)
.then(function(model, blah) {
res.json(model);
});
},
remove: function(req, res, next) { res.json(); }
};
// routes.js
var express = require('express');
var router = express.Router();
var modelsController = require('./controllers/models');
router.get('/concepts', modelsController.find);
router.get('/concepts/:id', modelsController.get);
router.post('/concepts', modelsController.create);
router.post('/concepts/:id', modelsController.update);
router.put('/concepts/:id', modelsController.update);
router.patch('/concepts/:id', modelsController.patch);
router.delete('/concepts/:id', modelsController.remove);
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment