skip to Main Content

I am trying to create a (MERN stack) management system that keeps track of vacant rooms in a hotel.

I am trying to change the roomTypeAOccupiedTotal from 2 to 3.

From the client side, it sends an axios.put()request as follows:

 axios
      .put(`http://localhost:8082/api/myHotel/${branchStatus.id}`, data)

this is the server-side code:

router.put('/:_id', (req, res) => {

  /*
  req.params looks like this:
  { _id: '63b4d533fabbf31cdb519896' }

  req.body looks like this:
  roomOccupied5F: 3,
  roomOccupied6F: 5,
  roomTypeAOccupiedTotal: 2,
  roomTypeBOccupiedTotal: 8,
  */
  
  let filter = { _id: mongoose.Types.ObjectId(req.params._id) }
  let update = { $set: req.body } 

  MyHotel.findByIdAndUpdate(filter, update, {new: true})
  .then(data => res.json({ msg: 'updated successfully' }))
  .catch(err =>
    res.status(400).json({ error: 'Unable to update the Database' })
  );

Below are the GET request and PUT request sent using POSTMAN.
after the message "updated successfully", I sent another GET request to check, but there are no changes to the variable(roomTypeAOccupiedTotal).

Could someone help me with solving this problem? the findByIdAndUpdate() method is working, as its not throwing any errors, but its not updating.

enter image description here
enter image description here
enter image description here

2

Answers


  1. I believe your problem is the filter object. Looking at the docs for findByIdAndUpdate, it expects to receive the id param, not a filter object.

    https://mongoosejs.com/docs/api/model.html#model_Model-findByIdAndUpdate

    Parameters:

    id «Object|Number|String» value of _id to query by

    Additionally, when you create an objectId out of the request param, you aren’t creating a new instance of it, so whatever was passed in would have failed to match anything. My IDE highlights this for me:

    enter image description here

    Your fix is likely something like this:

    const id = new mongoose.Types.ObjectId(req.params._id)
    MyHotel.findByIdAndUpdate(id, update, {new: true})
    
    Login or Signup to reply.
  2. No need to convert id, and no need to use the update operator(i.e. $set).

    try this:

    MyHotel.findByIdAndUpdate(req.params._id, req.body, { new: true }, (err, hotel) => {
        if (err) {
            console.log(err);
        } else {
            console.log(hotel);
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search