findByIdAndUpdate() method does not update the collection

Issue

So, I’m trying to update a product with mongodb and redux, but when I try to update the product, the database doesn’t seem to change. I can’t solve this, please can you help me?

Below I have my product.js file:

//UPDATE

router.put('/:id', verifyTokenAndAdmin, async (req, res) => {
  try {
    const updatedProduct = await Product.findByIdAndUpdate(
      req.params.id,
      {
        $set: req.body,
      },
      { new: true }
    );
    res.status(200).json(updatedProduct);
  } catch (err) {
    res.status(500).json(err);
  }
});

apiCalls.js:

export const updateProducts = async (id, product, dispatch) => {
  dispatch(updateProductStart());
  try {
    const res = await userRequest.put(`/products/${id}`);
    dispatch(updateProductSuccess({ id, product }));
  } catch (error) {
    dispatch(updateProductFailure());
  }
};

requestMethods.js:

import axios from 'axios';

const BASE_URL = 'http://localhost:5000/api/';
const TOKEN =
  JSON.parse(JSON.parse(localStorage.getItem('persist:root')).user).currentUser
    .accessToken || '';

// set token
localStorage.setItem('ACCESS_TOKEN', TOKEN);

// get token
const myToken = localStorage.getItem('ACCESS_TOKEN');

export const publicRequest = axios.create({
  baseURL: BASE_URL,
});

export const userRequest = axios.create({
  baseURL: BASE_URL,
  headers: { token: `Bearer ${myToken}` },
});

Solution

Change updateProducts as below. Notice there is a second parameter given to put. This would be equal to req.body in the backend part.

export const updateProducts = async (id, product, dispatch) => {
  dispatch(updateProductStart());
  try {
    const res = await userRequest.put(`/products/${id}`, product);
    dispatch(updateProductSuccess({ id, product }));
  } catch (error) {
    dispatch(updateProductFailure());
  }
};

And in the backend try changing findByIdAndUpdate as below. And before log req.body to see if you are getting the data.

const updatedProduct = await Product.findByIdAndUpdate(req.params.id, req.body);

Answered By – yousoumar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published