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
Looking at your schema you have an array of
carts
objects, each with a property ofitems
that is of typeObjectId
. You can usefindByIdAndUpdate
, which you will need toawait
, and then$pull
the object form the array like so:You can try with this:
This should remove the item from the carts array.