Created
August 8, 2017 07:03
-
-
Save fracarma/8ae056ead4c64f7a5a3a56038666844f to your computer and use it in GitHub Desktop.
Express-mongoose standard crud operations
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
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