Home > Enterprise >  How to Delete multiple user from table using checkbox in react and nodejs , mongoose
How to Delete multiple user from table using checkbox in react and nodejs , mongoose

Time:09-22

I am handling selected users id using checkbox in the table but when i send request to server to delete them all , i have no idea how to handle with nodejs using mongoose. Can anyone help me? Here is FE code:

const Home =()=> {
const [isChecked, setisChecked] = useState([]);
const handleDeleteUser = async () => {
    const response = await fetch(`http://localhost:3001/users/deleteUsers`, {
      method: "DELETE",
      body: JSON.stringify(isChecked),
      headers: {
        "Content-Type": "application/json",
      },
    });
  };

  const handlecheckbox = (e) => {
    const { value, checked } = e.target;
    console.log(value);
    if (checked) {
      setisChecked([...isChecked, value]);
    } else {
      setisChecked(isChecked.filter((e) => e !== value));
    }
  };
 return (
           <tbody>
              {users.map((user) => (
                <tr key={user._id}>
                  <td>
                    <Form.Group>
                      <Form.Check
                        type="checkbox"
                        value={user._id}
                        checked={user.isChecked}
                        onChange={(e) => handlecheckbox(e)}
                      />
                    </Form.Group>
                  </td>
                  <td>{user._id}</td>
                  <td>{user.name}</td>
                  <td>{user.email}</td>
                  <td>{user.lastLogin}</td>
                  <td>{user.createdAt}</td>
                  <td>{user.status}</td>
                </tr>
              ))}
            </tbody>
 )
}

Here Nodejs code :

userRouter.delete('/deleteUsers', async(req,res,next)=> {
  try {
    const selectedUsers = req.body
   
  } catch (error) {
    next(error) 
  }
})

CodePudding user response:

Assuming selectedUsers in the route is an array of ids, the following line should do the trick, if you want to do hard-delete.

await User.deleteMany({ _id: { $in: selectedUsers } });

More commonly, people want to do soft-delete where they define an isDeleted property on the schema as a Boolean, and then do the following:

await User.updateMany({ _id: { $in: selectedUsers } }, { isDeleted: true });
  • Related