Skip to content

Instantly share code, notes, and snippets.

@fracarma
Created August 8, 2017 07:03
Show Gist options
  • Save fracarma/8ae056ead4c64f7a5a3a56038666844f to your computer and use it in GitHub Desktop.
Save fracarma/8ae056ead4c64f7a5a3a56038666844f to your computer and use it in GitHub Desktop.
Express-mongoose standard crud operations
module.exports = function(Model) {
var module = {};
module.getAll = function(req, res) {
Model.find({}, function(err, data) {
if (err) {
res.status(500).json(err);
return;
}
res.status(200).json(data);
});
}
module.getById = function(req, res) {
Model.find({
_id: req.query.Id
}, function(err, data) {
if (err) {
res.status(500).json(err);
return;
}
if (!data) {
res.status(200).json('Cannot find the data');
return;
}
res.status(200).json(data);
});
}
module.create = function(req, res) {
var newModel = new Model(req.body);
newModel.save(function(err) {
if (err) {
res.status(500).json(err);
return;
}
res.status(201).json(newModel);
});
}
module.update = function(req, res) {
Model.findOne({
_id: req.body._id
}, createSelect(req), function(err, data) {
if (err) {
res.status(500).json(err);
}
if (!data) {
res.status(200).json('Cannot find the data');
return;
}
for (var key in req.body) {
if (req.body.hasOwnProperty(key)) {
if (Model.changesNotAllowed.indexOf(key) != -1) {
continue;
}
data[key] = req.body[key];
}
}
data.save(function(err) {
if (err) {
res.status(500).json(err);
return;
}
res.status(200).json('Data updated');
});
});
}
module.delete = function(req, res) {
Model.remove({
_id: req.query.Id
}, function(err, data) {
if (err) {
res.status(500).json(err);
return;
}
if (!data) {
res.status(200).json('Cannot find the data');
return;
}
res.status(200).json('Data deleted');
});
}
/** Return an object with the request structure but with values equals = "1" */
function createSelect(req) {
var select = {};
for (var key in req.body) {
if (req.body.hasOwnProperty(key)) {
if (Model.changesNotAllowed.indexOf(key) != -1) {
continue;
}
select[key] = "1";
}
}
return select;
}
return module;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment