'How can I send updated object from subdocument array of objects using mongoose as response
I want to send updated object as response from subdocument.
From my carts model, I am querying the subdocument array which is cartItems. After querying and doing crud operation, I don't want to send the full cartItems array as response. I want to send the updated object as response.
exports.removeCartItem = async (req, res) => {
const { itemId } = req.params
const { email } = req.user
const { id } = req.body
const targetUser = await User.findOne({ email }).exec()
const cartItemRemoved = Cart.findOneAndUpdate(
{
user: targetUser._id,
},
{
$pull: { cartItems: { _id: itemId } },
},
{ new: true },
).exec((err, data) => {
if (err) {
console.log(er)
}
res.json(data)
})
}
This is the response I am getting right now:
{
"user": "621def0665c08eff01794f6e",
"cartItems": [
{
"product": "6228edb603d5e7ca773a2b04",
"quantity": 5,
"price": 200,
"_id": "622b04741bab0093c963ef18"
}
],
"_id": "622b04741bab0093c963ef17",
"__v": 0
}
I want send the updated object as response - something like below:
{
"product":"6228edb603d5e7ca773a2b04",
"quantity": 5,
"price": 200,
"_id": "622b04741bab0093c963ef18"
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
