I have a Map document with a number of Layer sub-documents and want to implement HTTP PATCH, so only given attributes of the JSON should update the Layer sub-document. The following code works, but I have to specify each attribute that can be changed. Is there a better way to do it?
var update = {};
if (req.body.name !== undefined)
update['layers.$.name'] = req.body.name;
if (req.body.isDefault !== undefined)
update['layers.$.isDefault'] = req.body.isDefault;
if (req.body.isPublic !== undefined)
update['layers.$.isPublic'] = req.body.isPublic;
Map.model.findOneAndUpdate({_id: req.params.mapId, 'layers._id': req.params.layerId}, update, callback);
You can make a function like this:
function updateParams(reqParams,additionalInfo)
{
var update = {};
for(var paramName in reqParams)
{
if(reqParams.hasOwnProperty(paramName))
{
if(reqParams[paramName]!==undefined)
{
update[additionalInfo+paramName] = reqParams[paramName];
}
}
}
return update;
}
updateParams(req.body,'layers.$.');
I have you considered JsonPatch this project converts json patch to mongo atomic updates: jsonpatch-to-mongodb