Hyrax
Hyrax

Reputation: 13

findOneAndDelete Mongoose not working MERN stack

GoodDay Experts,

I've tried following code but it did not work, and it gives me null value.. maybe my routes are wrong but basically it works the way on other routes... and here is my backend for delete case: manage.js/actions

export const removeRecipient = (payload) => async (dispatch) => {
  try {
    const res = await axios.delete(
      `${_config.MAT_URL}/api/1/customer/delete`,
      payload
    );
    dispatch({
      type: DELETE_CUSTOMER,
      payload: res.data,
    });
  } catch (err) {
    dispatch({
      type: POST_ERROR,
      payload: { err },
    });
  }
};

and for my routes which is the mongoose query for findOneAndDelete, under customer.js :

   router.delete("/delete", (req, res) => {
  Customer.findOneAndDelete({ _id: req.params.id }, (err, Customer) => {
    if (!err) {
      res.json({ msg: "customer deleted", deleted: Customer });
    } else {
      console.log("Error removing :" + err);
    }
  });
});

And for the front end im using "AiOutlineDelete" which was coded as :

  const handleDelete = (id) => {
    console.log('delete')
    removeRecipient(id)
  }

<a
  id={`delete-${rowIndex}`}
  className="anchor-action-delete"
  href="#foo"
  onClick={(e) => {
    e.preventDefault();
    handleDelete(row);
  }}>

thanks have a great day

Upvotes: 1

Views: 4115

Answers (2)

Tom Slabbaert
Tom Slabbaert

Reputation: 22296

There are 2 problems in your code:

  1. req.params.id is meant for urls of the form /delete/:id which is obviously not your route, you should change it to req.query.id instead which matches query parameters in the url such as /delete?id=123.

  2. The default type of _id is ObjectId, under the assumption you did not change this you need to cast your req.query.id which is type string to ObjectId.

It looks like you're using mongoose so here's mongoose syntax:

const mongoose = require("mongoose");

router.delete("/delete", (req, res) => {
    Customer.findOneAndDelete({ _id: new mongoose.Types.ObjectId(req.query.id) }, (err, Customer) => {
        if (!err) {
            res.json({ msg: "customer deleted", deleted: Customer });
        } else {
            console.log("Error removing :" + err);
        }
    });
});

For nodejs native Mongo package:

import {ObjectId} from "mongodb";
...

new ObjectId(req.query.id)

Upvotes: 3

SathwikaRao
SathwikaRao

Reputation: 153

I dont see you sent the id to the backend but you are trying to retrieve it from req.params.id try passing the id like "delete/:id" at the end of the link and specify this in the routes aswell.

if that doesnt fix try the below code this for routes

if nothing works check this, In the component you need to send the id(object id) but i see "row" what is the value of row? if the row value is not the id in the database then it wont delete. if this your issue try inspecting the code by keeping breakpoints or write a console.log() to check the value of "row" .

    try {
        const removedProject = await Customer.remove({
            _id: req.params.id
        })
        res.json(removedProject)
    } catch (err) {
        res.json({
            message: err
        })
    }

Upvotes: 0

Related Questions