CRUD/Node Express MongoDB

14. Find and Update

Jeungbin Han 2022. 7. 29. 12:07

https://www.youtube.com/watch?v=W1Kttu53qTg I learned everything from this tutorial and I don't need to mean to get money to write the blog. It's everything for myself studying and to remain that. 

 

controller.js

Find

// retrieve and return all users/ retrive and return a single user
exports.find = (req, res) => {
  Userdb.find()
    .then((user) => {
      res.send(user);
    })
    .catch((err) => {
      res
        .status(500)
        .send({
          message:
            err.message || "Error Occurred while retriving user information",
        });
    });
};

There are two types of route parameters, URL parameters, and query parameters.

In this project, we are using 'URL' parameters.

route.put("/api/users:/id", controller.update);

req.params.id => It means that url's id // 'users' is database accessing name. 

users:/id means the specific id inside the users database. 

 

controller.js

Update

exports.update = (req, res) => {
  if (!req.body) {
    return res.status(400).send({ message: "Data to update can not be empty" });
  }

  const id = req.params.id;
  Userdb.findByIdAndUpdate(id, req.body, { useFindAndModify: false })
    .then((data) => {
      if (!data) {
        res
          .status(404)
          .send({
            message: `Cannot Update user with ${id}. Maybe user not found!`,
          });
      } else {
        res.send(data);
      }
    })
    .catch((err) => {
      res.status(500).send({ message: "Error Update user information" });
    });
};

findByIdAndUpdate has first parameter => select id 

second => change content