MERN Delete request issues

Viewed 32

I'm wokring on a simple suggestion app it has authenctication and context api for State management, I can create, read, update and delete a suggestion but I've been trying to make a delete request but its not working. I console.log the error message due to the conditional statement and its saying Request failed with status code 403 I've tried everything but its not working

this is my code on expresss

router.delete("/bmi/delete/:id", async (req, res) => {
  const id = req.params.id;
  try {
    const suggest = await bmiCalc.findById(id);
    if (suggest.userId === req.body.userId) {
      await suggest.deleteOne();
      res.status(200).json("Suggestion deleted");
    } else {
      res.status(403).json("Not your Suggestion to delete");
    }
  } catch (error) {
    res.status(500).json("Error from server");
  }
});

This is the react axios request

const Home = () => {
  const { user } = useContext(AuthContext);
  const [data, setData] = useState([]);
const handleSuggestion = async (e) => {
    e.preventDefault();

    const fullDetail = {
      userId: user.users._id,
      bmiNumber: bmiNumber.current.value,
      country: country.current.value,
      messages: messages.current.value,
    };
    const res = await axios.post(
      "http://localhost:5000/app/bmi/bmiform/create",
      fullDetail,
    );
    setData([...data, res.data]);
    console.log(res.data);
  };

  const reload = () => {
    window.location.reload();
  };

  useEffect(() => {
    const getSuggestion = async () => {
      const res = await axios.get(
        `http://localhost:5000/app/bmi/all/${user.users._id}`,
      );
      await setData(res.data);
    };
    getSuggestion();
  }, [user.users._id]);

  const handleDelete = async (id) => {
    try {
      await axios.delete(`http://localhost:5000/app/bmi/delete/${id}`, {
        data: { userId: user.users._id },
      });

      setData(data.filter((post) => post._id !== id));
    } catch (err) {
      console.log(err.message);
    }
  };

I'm using chakra UI, here is the button for the onclick event


<Flex
        w={"100%"}
        h={"60vh"}
        padding={"8px"}
        gap={"8px"}
        flexWrap={"wrap"}
        justifyContent={"flex-start"}>
        {data.map((data) => {
          return (
            <Box
              key={data._id}
              width={["47%", "55%", "25%", "24%"]}
              height={["55%", "50%", "50%", "50%"]}
              bg={"#ffffff"}
              display={"flex"}
              flexDirection={"column"}
              borderRadius={7}
              gap={4}
              padding={5}>
              <Box w={"100%"} h={"5vh"} transition={"0.3s all"}>
                <p className='boxTitle'> BMI: {data.bmiNumber}</p>
                <p className='boxCountry'> {data.country}</p>
              </Box>
              <Box width={"100%"} height={"100%"} paddingTop={2}>
                <p className='boxMessage'> {data.messages}</p>
              </Box>
              <Flex width={"100%"} gap={1}>
                <Button
                  bg={"#541db5"}
                  type='submit'
                  width='100%'
                  outline='none'
                  border='none'
                  borderRadius={6}
                  color='#ffffff'
                  fontSize={20}
                  fontWeight={600}
                  marginBottom={4}
                  padding={4}>
                  edit
                </Button>
                {data.userId === user?.users._id && (
                  <Button
                    onClick={() => handleDelete(data._id)}
                    type='submit'
                    width='100%'
                    outline='none'
                    border='none'
                    borderRadius={6}
                    color='#ffffff'
                    fontSize={20}
                    fontWeight={600}
                    bg='#ef233c'
                    marginBottom={4}
                    padding={4}>
                    <DeleteIcon />
                  </Button>
                )}
              </Flex>
            </Box>
          );
        })}
      </Flex>
3 Answers

try console logging both of these too see why they are not equal.

suggest.userId

req.body.userId

Then investigate why they are not equal.

I just had this issue and fixed it a couple of minutes ago.

So basically MongoDB doesn't see those objectIds as equal

The best option to compare them is using suggest.userId.equals(req.body.userId) this will result in true

In your router you need to access userId as

 req.body.data.userId

instead of

req.body.userId
Related