JSON-Patch
JSON-Patch copied to clipboard
JSON-Patch Node.js add element to object
i'am trying to use fast-json-patch lib in node.js but no operation works for me. I think i have missing something in my code.
router.patch('/user/:uid', (req, res) => {
var patches = [
{
op: 'add',
path: '/favoris',
value: { user_id: req.params.uid, parking_id: req.body.parking_id }
}
];
jsonpatch.applyOperation(req.body, patches).newDocument;
if (!errors.isEmpty()) {
return res
.status(httpStatusCodes.UNPROCESSABLE_ENTITY)
.send({ errors: errors.array() })
.end();
}
});
Hi!
You're misusing applyOperation
function. applyOperation
applies a single operation not an array of operations (patch). If you want to apply an array please use applyPatch
, otherwise pass a single operation object to applyOperation
.
The end result is:
router.patch('/user/:uid', (req, res) => {
var operation = {
op: 'add',
path: '/favoris',
value: { user_id: req.params.uid, parking_id: req.body.parking_id }
}
jsonpatch.applyOperation(req.body, operation).newDocument;
if (!errors.isEmpty()) {
return res
.status(httpStatusCodes.UNPROCESSABLE_ENTITY)
.send({ errors: errors.array() })
.end();
}
});
thanks fro replying, but i always get the same status error Status: 500 Internal Server Error