DEV Community

Margaret W.N
Margaret W.N

Posted on

Habit tracker API: Updating data

A simple semantic error cost me so much trouble yesterday. I simply had to switch res and req in the get arrow function ~ I owe the observation to @drumzminister: appreciated.

.get((req, res) => res.json(req.habit))
Enter fullscreen mode Exit fullscreen mode

Get by Id function is officially working.

Alt Text

I handled updating data:

  • Put function
.put((req, res) => {
    const { habit } = req;

    habit.title = req.body.title;
    habit.description = req.body.description;
    habit.done = req.body.done;

    habit.save((err) => {
      if (err) {
        return res.sendStatus(404);
      }
      return res.json(habit);
    })
  })
Enter fullscreen mode Exit fullscreen mode
  • Patch function
.patch((req, res) => {
    const { habit } = req;

    if (!req.body._id) {
      delete req.body._id
    }
    Object.entries(req.body).forEach((property) => {
      const key = property[0];
      const value = property[1];
      habit[key] = value;
    })

    req.habit.save((err) => {
      if (err) {
        return res.sendStatus(404);
      }
      return res.json(habit);
    })
  })
Enter fullscreen mode Exit fullscreen mode
  • Delete function
 .delete((req, res) => {
    req.habit.remove((err) => {
      if (err) {
        return res.send(err);
      }
      return res.sendStatus(204);
    });
  });
Enter fullscreen mode Exit fullscreen mode

And In the spirit of experimenting I added data to my database from a json file:
Image

I love days like this, ending a day with no red lines!

Day 12

Top comments (0)