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);
}
});
3
Answers
cartItem at this point is a Mongoose Document and not a regular JSON object.
A way to approach this problem is to first convert the cartItem to a JSON string and allow you to modify key-value pairs as required.
You can do so by :
This will convert the Mongoose Model (a javascript value) to a JSON string.
If you wish to parse the value before adding it to the cart, this can be achieved like this:
This constructs a JavaScript value/ object which is described by the string in this case the output from
JSON.stringify(cartItem);
Here’s some more relevant info for working with Mongoose objects in JS: convert mongodb object to javascript object
According to answers on there you can use the ToJSON() function to convert to json, or .toObject() to convert to a javascript object.
If you are using
mongoose
, then you can uselean()
to get plain object.for ex:
and then you can add properties: