0

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
  • 1
    Are you using any ORM like mongoose to connect to mongodb? Commented Aug 21, 2023 at 2:15
  • Yes, I am using mongoose Commented Aug 21, 2023 at 2:24
  • Can you share your getItemById() code? Commented Aug 21, 2023 at 2:25

2 Answers 2

2

If you are using mongoose, then you can use lean() to get plain object.

for ex:

const car = await Car.findOne().lean();

and then you can add properties:

car['new_prop'] = 'new_data';
Sign up to request clarification or add additional context in comments.

1 Comment

This is the common practice for such cases (not the selected answer)
1
 const cartItem = await getItemById(item.itemId); 

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 :

const cartItemv2 = JSON.stringify(carItem); 

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:

const cartItemv2 = JSON.parse(JSON.stringify(cartItem));

This constructs a JavaScript value/ object which is described by the string in this case the output from JSON.stringify(cartItem);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.