Skip to content

Instantly share code, notes, and snippets.

@select
Last active November 9, 2016 15:46
Show Gist options
  • Save select/ccd8032237d1d9eef17b to your computer and use it in GitHub Desktop.
Save select/ccd8032237d1d9eef17b to your computer and use it in GitHub Desktop.
Express Mongo REST API in ES6 with co and generators mongoose and lodash
'use strict';
let router = require('express').Router();
const co = require('co');
const mongoose = require('mongoose');
const Box = mongoose.model('Box');
const _ = require('lodash');
// ---
router.route('/')
// ##create
.post(function(req, res) {
co(function * () {
let box = new Box(req.body); // create a new instance of the Box model
try {
res.json(yield box.save());
} catch(e) {
res.json({errors: e});
}
});
})
// ## get all
.get(function(req, res) {
co(function * () {
try {
res.json(yield Box.find());
} catch(e) {
res.json({errors: e});
}
});
});
// ---
router.route('/:_id')
// ## get the box with this id
.get(function(req, res) {
co(function * () {
try {
res.json(yield Box.findById(req.params._id));
} catch(e) {
res.json({errors: e});
}
});
})
// ## update/patch the box with this id
.put(function(req, res) {
co(function * () {
try {
let box = yield Box.findById(req.params._id);
_.assignIn(box, req.body);
res.json(yield box.save());
} catch(e) {
res.json({errors: e});
}
});
})
// ## delete the box with this id
.delete(function(req, res) {
co(function * () {
try {
res.json(yield Box.remove({_id: req.params._id }));
} catch(e) {
res.json({errors: e});
}
});
});
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment