0

I am using nodeJS and for life of me I have no idea why my array is not being modified.

The below is my code

router.get('/cart', (req, res) => {
    let cart = req.session.cart;

    let cartKeys = Object.keys(cart);

    Product.find({_id: {$in:cartKeys}}, (err, productResults) => {
        if(err)throw err;

        let newProductsArray = [];

        for(let index in productResults){
            let curProduct = productResults[index];

            curProduct['quantity'] = cart[curProduct._id];
            console.log(cart[curProduct._id])    //prints out quantity e.g. 4

            console.log(curProduct.quantity)      //prints out same quantity as above

            console.log(curProduct)  // Doesn't have field 'quantity'

            newProductsArray.push(curProduct)
        }

        console.log(newProductsArray)    //none of the products have 'quantity'
        res.render('./shop/cart/cart' , {
            js:['/shop/cart/cart.js'],
            css:['/shop/cart/cart.css']
        })
    });
});

Everything else is working great. I can access the route, I find all three products that I am supposed to find and it is sotred in productResults. The problem is that both console.log(curProduct) and console.log(newProductsArray) (I tried making a new array because I could not modify productResults) they both do not have the field quantity. Even stranger thing is that console.log(cart[curProduct._id]) prints out the quantity just fine. What am I doing wrong? I am quite sure I have been doing similar works this way.

Even stranger thing is that console.log(curProduct.quantity) prints out same result as line above it.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
forJ
  • 4,309
  • 6
  • 34
  • 60
  • You need to use [`.lean()`](http://mongoosejs.com/docs/api.html#query_Query-lean) in order to return plain JavaScript objects. Otherwise these are actually "mongoose documents" which are complex objects that merely have accessors and a serialization that makes them "appear" as plain objects. Using `.lean()` makes them plain so you can alter them. – Neil Lunn Sep 05 '17 at 12:22
  • @NeilLunn thank god... I thought my computer was broken. I didn't even search in that direction because I didn't even think that way. Thank you so much I spent so much time trying to make this work... – forJ Sep 05 '17 at 12:24

0 Answers0