loading...

Habit tracker API: Updating data

mtee profile image Margaret W.N ・1 min read

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))

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);
    })
  })
  • 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);
    })
  })
  • Delete function
 .delete((req, res) => {
    req.habit.remove((err) => {
      if (err) {
        return res.send(err);
      }
      return res.sendStatus(204);
    });
  });

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

Posted on by:

mtee profile

Margaret W.N

@mtee

Developer | GADs 20 scholar | Diving into backend

Discussion

markdown guide