Skip to content

Instantly share code, notes, and snippets.

@developit
Last active December 25, 2018 22:01
Show Gist options
  • Save developit/ec2f438efc5feea4fd3a to your computer and use it in GitHub Desktop.
Save developit/ec2f438efc5feea4fd3a to your computer and use it in GitHub Desktop.
mongoose-resource
import mongooseResource from '../lib/mongoose-resource';
import Foo from '../models/foo'; // a mongoose Model
export default mongooseResource('foo', Foo);
import resource from 'resource-router-middleware';
import { toRes } from './util';
export default function(name, model) {
return resource({
id : name,
list({ params }, res) {
var limit = Math.max(1, Math.min(50, params.limit|0 || 10));
if (params.search) {
return model.textSearch(params.search, {
limit : limit,
language : 'en',
lean : true
}, toRes(res));
}
model.find({}).skip(params.start|0 || 0).limit(limit).exec(toRes(res));
},
create({ body }, res) {
model.create(body, toRes(res));
},
read({ params }, res) {
model.findById(params[name], toRes(res));
},
update({ body, params }, res) {
delete body._id;
model.findByIdAndUpdate(params[name], { $set:body }, toRes(res));
},
delete(req, res) {
model.findByIdAndRemove(params[name], toRes(res));
}
});
}
@gwmccull
Copy link

the read(), update() and delete() functions are using this.id but since id is in the same object, I don't believe you can reference it in that manner. I think it works better if you use name instead.

@developit
Copy link
Author

@gwmccull - good catch, updated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment