skip to Main Content

I want to remove an object from my array. First, I want to find the customer by their ID, and then within the customer model in the array of carts, I want to delete one of the items based on the ID.

This is carts array in customer model :

   carts: [
      {
        items: {
          type: mongoose.Schema.Types.ObjectId,
          ref: "Cart",
        },
        amount: { type: Number, default: 1 },
      },
    ],

And this is delete Controller :

//delete bag item
export const deleteCartItemCtrl = asyncHandler(async (req, res) => {
  const { userId, id } = req.body;
  try {
    const user = Customers.updateOne(
      { _id: userId },
      {
        $pull: {
          carts: { items: [{ _id: id }] },
        },
      }
    );
    res.json({
      status: "success",
      message: "cartItem delete successfully",
    });
  } catch (error) {
    console.log(error),
      res.status(500).json({
        status: "error",
        message: "An error occurred while cart item delete",
      });
  }
});

I used "pull", but the item I want to delete isn’t getting removed.

2

Answers


  1. Looking at your schema you have an array of carts objects, each with a property of items that is of type ObjectId. You can use findByIdAndUpdate, which you will need to await, and then $pull the object form the array like so:

    const user = await Customers.findByIdAndUpdate(userId,
       {
          $pull: {
             carts: {
                items: id
             },
          }
       },
       { new : true }
    );
    
    Login or Signup to reply.
  2. You can try with this:

    const user = await Customers.updateOne(
        {_id: userId},
        {
            $pull: {
                carts: { items: id }
            }
        })
    

    This should remove the item from the carts array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search