[Fixed] Deleting Order Items from Orders

Issue

I have the following JSON stored in mongodb

[
    {
        "orderItems": [
            "606808d2d7351b0c52d38634",
            "606808d2d7351b0c52d38635"
        ],
        "status": "Pending",
        "_id": "606808d2d7351b0c52d38636",
        "shippingAddress1": "Flowers Street , 45",
        "shippingAddress2": "1-B",
        "city": "Thessaloniki",
        "zip": "00000",
        "country": "Greece",
        "phone": "+00302410551416",
        "user": {
            "_id": "6062d46da91a58067da5dfc2",
            "name": "Vasilis",
            "id": "6062d46da91a58067da5dfc2"
        },
        "dateOrdered": "2021-04-03T06:18:58.879Z",
        "__v": 0,
        "id": "606808d2d7351b0c52d38636"
    }
]

I can delete the order, no problem with that

router.delete('/:id', (req, res) => {
    Order.findByIdAndRemove(req.params.id)
    .then((order) => {
        if(order) {
            res.status(200).json({
                success: true,
                message: 'The order is deleted'
            })
        } else {
            res.status(404).json({
                success: false,
                message: 'order not found'
            })
        }
    }).catch((err) => {
        return res.status(400).json({
            success: false,
            error: err
        })
    })
})

Now I want to change the above code, so as to delete the orderItems as well. how to do that?

Thanks,
Theo

Solution

You can use Model.deleteMany to delete the OrderItems (I’m guessing that’s the model name) after deleting the Order document. And you don’t have to call status(200) on the response object since it’s automatically set when calling res.json.

router.delete('/:id', async (req, res) => {
  try {
    const order = await Order.findByIdAndRemove(req.params.id)
    if (!order) {
      return res.status(404).json({
        success: false,
        message: 'Order not found',
      })
    }

    await OrderItem.deleteMany({ _id: { $in: order.orderItems } })

    res.json({
      success: true,
      message: 'Order deleted',
    })
  } catch (err) {
    return res.status(500).json({
      success: false,
      error: err,
    })
  }
})

Leave a Reply

(*) Required, Your email will not be published