this is the document where i have a sub document as cartItems.
i want send the specific object as response from this cart item array.
but when i am using aggregate i am getting the empty array as response.
this is my controller part. i tried in two ways for my expected response.
exports.getSingleItem = async (req, res) => {
const { itemId } = req.params
const { email } = req.user
const targetUser = await User.findOne({ email }).exec()
const singleItem = await Cart.aggregate([
{
$match: {
user: targetUser.id,
},
},
{
$replaceRoot: {
newRoot: {
$first: {
$filter: {
input: '$cartItems',
as: 'item',
cond: {
$eq: ['$$item._id', itemId],
},
},
},
},
},
},
])
res.json(singleItem)
}
this is the secound way which i tried.
const isCartExist = await Cart.aggregate([
{
$match: {
' user': targetUser._id,
},
},
{
$unwind: '$cartItems',
},
{
$match: {
'cartItems._id': itemId,
},
},
{
$replaceRoot: {
newRoot: '$cartItems',
},
},
]).exec((err, item) => {
if (err) {
console.log(err)
} else {
res.json(item)
console.log(item)
}
})