ga-wdi-boston / team-project

Other
2 stars 39 forks source link

[express/mongoose] - How do I get the update action to send back the JSON for the updated resource #325

Closed aprilsourz closed 7 years ago

aprilsourz commented 7 years ago

I want the update action in in our Items controller to send back the JSON for the item that was updated.

I am able to make to update an an item successfully and get back a 204 when my the controller code looks like :

const update = (req, res, next) => {
  delete req.body._owner;  // disallow owner reassignment.
  req.item.update(req.body.item)
    .then(() => res.sendStatus(204))
    .catch(next);
};

This is my attempt to get back a JSON response from the update action.

const update = (req, res, next) => {
  delete req.body._owner // disallow owner reassignment.
  let item = Object.assign(req.body.item)
  console.log(item)
  req.item.update(req.body.item)
    .then((item) =>
      res.status(200)
        .json({
        item: item.toJSON({ virtuals: true, user: req.user }),
      }))

    .catch(next);
};

I get a 500 and the error in my chrome console is:

{"error":{"message":"item.toJSON is not a function","error":{}}}"

I am a little stumped. I'll keep googling for an answer and looking at the mongoose documentation. Any advice on where to look for the answer? I'm calling toJSON on something that doesn't have that method. How can i access the updated item from the database in the response?

benjimelito commented 7 years ago

When you simply return item in your .then statement, is it not in the correct format?

aprilsourz commented 7 years ago

I found a work around. I will test that out too. Thank you.