JSON-Patch icon indicating copy to clipboard operation
JSON-Patch copied to clipboard

JSON-Patch Node.js add element to object

Open hathemi opened this issue 6 years ago • 2 comments

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();
  }
});

hathemi avatar Dec 03 '18 08:12 hathemi

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();
  }
});

alshakero avatar Dec 03 '18 15:12 alshakero

thanks fro replying, but i always get the same status error Status: 500 Internal Server Error

hathemi avatar Dec 04 '18 08:12 hathemi