Search code examples
javascriptnode.jsmongodbexpressmongoose

Delete specific object in array element in document and save mongoose


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.


Solution

  • 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 }
    );