TypeError:无法读取未定义的属性“ price”

时间:2019-01-19 09:15:06

标签: javascript node.js

我正在创建一个在线商店来学习node.js。当我从products.json文件删除产品时,cart.json中的相应产品也会被删除。尝试删除产品时,图片中出现以下错误。这是代码!

在products.ejs中

<form action="/admin/delete-product" method="POST">
  <input type="hidden" name="productId" value="<%=product.id%>">
  <button class="btn" type="submit">Delete</button>
</form>

链接控制器后,在控制器功能中 在admin.js控制器中,

// import product model
const Product = require('../models/product');
// delete a product
exports.postDeleteProduct = (req, res) => {
  const prodId = req.body.productId;
  Product.deleteById(prodId, () => {
    res.redirect('/admin/products');
  });
}

然后在product.js模型中,

// import cart model
const Cart = require('./cart');

// get all the products from the file

const getProductsFromFile = cb => {
  fs.readFile(p, (err, fileContent) => {
    if (err) {
      cb([]);
    } else {
      cb(JSON.parse(fileContent));
    }
  });
};

// delete by id

static deleteById(id, callback) {
    getProductsFromFile(products => {
      const product = products.find(prod => prod.id == id);
      const updatedProducts = products.filter(prod => prod.id !== id);
      fs.writeFile(p, JSON.stringify(updatedProducts), err => {
        if (!err) {
          console.log('Product: ',product);

          //also delete in the cart
          Cart.deleteProduct(id, product.price, callback);
        }
      })
    })
  }

执行代码后,出现以下错误。注意,“产品”有两个控制台输出。一个用于实际产品,第二个undefined(出于某种原因)!

enter image description here

1 个答案:

答案 0 :(得分:1)

static deleteById(id, callback) {
  console.log('deleteById', { id });
  getProductsFromFile(products => {
    let deletedProduct = null;
    let updatedProducts = [];

    for(const product of products) {
      if(product.id === id) {
        deletedProduct = product
      } else {
        updatedProducts.push(product);
      }
    }

    if (!deletedProduct) {
      console.log('deleteById: Product not found', { id });
      callback();
    } else {
      fs.writeFile(p, JSON.stringify(updatedProducts), err => {
        if (!err) {
          console.log('deleteById: Product', deletedProduct);
          Cart.deleteProduct(id, deletedProduct.price, callback);
        }
      });
    }
  })
}