Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

node.js - TypeError: Cannot read property on my nodejs API

Here is my code

async totalSum(req, res) {
    let userId = req.params.userId;
    let user = await User.findOne({userId:userId});
    if (user == null) {
      res.status(400).json({message:"User not found"});
    }

    let cartItem = await CartItem.find({
      userId: userId
    });
    var totalSum = 0;

    var x = 0;
    while (cartItem[x].productId) {
      console.log(cartItem[x].productId);
      let productId_x = cartItem[x].productId;
      console.log(productId_x);
      console.log(typeof productId_x);
      console.log(cartItem[x].quantity);
      let productId_x_quantity = cartItem[x].quantity;
      let product = await Product.findOne({
        productId: productId_x
      });
      console.log(product);
      console.log("yes");
      let productId_x_price = product.price;
      let mul_product = math.evaluate( productId_x_price * productId_x_quantity );
      console.log(typeof mul_product);
      totalSum += mul_product;
      console.log(totalSum);
      ++x;
    }
    console.log(totalSum);

    return res.status(200).json({Total: totalSum});
  }

I'm developing a eCommerce site, here the API is to calculate the total sum in cart items. First through params it will get the userId and finds the account in mongodb and then it finds the cart items from another collection, since it would be more item, I'm taking the values as a array and passing in a while loop. it will use the productId to find the price and calculate the total. I'm able to calculate the total and check it via logging but when api is testing using POSTMAN I'm getting a error

TypeError: Cannot read property 'productId' of undefined
 at totalSum (/home/abhi/getmayon/ecom/blockchainecommerce/loyalty-app-2/controllers/users.js:269:24)
 at processTicksAndRejections (internal/process/task_queues.js:93:5)

question from:https://stackoverflow.com/questions/65916970/typeerror-cannot-read-property-on-my-nodejs-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your While loop is running infinitive time as though x counter is just increasing there is no condition for stoping. I will suggest you to use map. as though you have got CartItem so value are present here . just map through the CartItem.

  cartItem.map((item)=>{
  let productId_x = item.productId;
  let productId_x_quantity = item.quantity;
  let product = await product.findOne({
    productId : productId_x
  });
 ...rest of code 
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...