Created
January 6, 2016 20:31
-
-
Save nmajor/91f4fd6788dce18b46ff to your computer and use it in GitHub Desktop.
Complete REST Routes and Methods for an Express.js + Mongoose.js API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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