skip to Main Content

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


  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);

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search