Skip to content

Instantly share code, notes, and snippets.

@remy
Last active April 21, 2017 16:00
Show Gist options
  • Save remy/6c49b83c071bf90dd108cc0cce555f57 to your computer and use it in GitHub Desktop.
Save remy/6c49b83c071bf90dd108cc0cce555f57 to your computer and use it in GitHub Desktop.
Quick and dirty mongoose crud interface.

Example usage

const express = require('express');
const List = require('../models/list');
const Crud = require('./crud');

const list = new Crud(List, { queryKey: 'publicId' });
const router = express.Router();
module.exports = router;

router.get('/', list.find(), (req, res) => res.jsonp(req.result));
router.post('/', list.create(), (req, res) => res.jsonp(req.result));
router.get('/:publicId', list.findOne(), (req, res) => res.jsonp(req.result));
router.put('/:publicId', list.update(), (req, res) => res.jsonp(req.result));
// TODO: router.delete('/:publicId', list.delete()); 

Obviously you'll need to add security layer!

class Crud {
constructor(collection, { db, resultKey = 'result', queryKey = 'id' } = {}) {
this.collection = collection;
this.queryKey = queryKey;
this.resultKey = resultKey;
}
findOne = () => (req, res, next) => {
this.collection.findOne({ [this.queryKey]: req.params[this.queryKey] }).then(doc => {
req[this.resultKey] = doc;
next();
}).catch(next);
}
find = () => (req, res, next) => {
this.collection.find().then(docs => {
req[this.resultKey] = docs;
next();
}).catch(next);
}
create = () => (req, res, next) => {
const c = new this.collection(req.body);
c.save().then(doc => {
req[this.resultKey] = doc;
next();
}).catch(next);
}
update = () => (req, res, next) => {
this.collection.findAndModify({
query: { [this.queryKey]: req.params[this.queryKey] },
update: { $set: req.body },
new: true
}).then(doc => {
req[this.resultKey] = doc;
next();
}).catch(next);
}
}
module.exports = Crud;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment