Struggling to add extra properties and values to the object returned from mongoDB database in NodeJs
It is a nodeJs project. There are few items stored in cart table in MongoDB database. The architecture is, the items are fetched from the cart table and then the id is used to fetch the whole details about the item from the item table and to see if they still exist as the item.
The item in the cart has few extra properties such as count and filter, which I want to add to the returned item from the item table. I have followed the following approach to achieve this feature. But it is not working as expected. Can someone help me out here please.
The code strcture goes as follow:
router.get("/", userAuth, async (req, res, next) => {
try {
console.log("running");
const { _id } = req.userInfo;
const cartItems = await getAllCartItems(_id);
const carts = [];
for (const item of cartItems) {
const cartItem = await getItemById(item.itemId);
if (cartItem?._id) {
cartItem.count = item.count;
cartItem.filter = item.filter;
carts.push(cartItem);
}
// console.log(cartItem);
}
carts.length >= 0 &&
res.json({
status: "success",
message: "cart items are returned",
carts,
});
} catch (error) {
next(error);
}
});
mongooseto connect to mongodb?getItemById()code?