You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js创建订单时报错:Cannot read properties of undefined (reading 'productName')

问题:通过selectedProductName查询产品信息时触发TypeError

我在将selectedProductName(例如'Black Jacket (M)')传入后续查询时遇到问题。需要通过selectedProductName从product表获取productName,再以此获取productID插入orders表(productID是orders表的外键)。前端会创建新客户并添加新订单信息。

相关代码

app.post("/create", async (req, res) => {
  console.log("Request Body:", req.body);

try {
const {
  quantity,
  orderStatus,
  custName,
  contactInfo,
  location,
  selectedProductName,
} = req.body;

console.log("Selected Product Name:", selectedProductName);
 
// Insert customer first
const insertCustomerQuery = `
  INSERT INTO customer (customerName, contactInformation, location)
  VALUES (?, ?, ?)
`;
const customerResult = await db.query(insertCustomerQuery, [
  custName,
  contactInfo,
  location,
]);
const customerId = customerResult.insertId;

// Get the product name from the selected product
const getProductQuery = `
  SELECT productName FROM product WHERE productName = ?
`;

console.log("Product Name Query:", getProductQuery);

const productNameResult = await db.query(getProductQuery, [
  selectedProductName,
]);
const productName = productNameResult[0].productName;

// Get product ID based on the obtained product name
const getProductIDQuery = `
  SELECT productID FROM product WHERE productName = ?
`;

console.log("Product ID Query:", getProductIDQuery);

const productIDResult = await db.query(getProductIDQuery, [
  productName,
]);
const productID = productIDResult[0].productID;

console.log("Product ID Result:", productIDResult);

// Insert order using the obtained customer ID and product ID
const insertOrderQuery = `
  INSERT INTO orders (orderStatus, orderQuantity, orderDate, productID, customerID)
  VALUES (?, ?, NOW(), ?, ?)
`;
await db.query(insertOrderQuery, [
  orderStatus,
  quantity,
  productID,
  customerId,
]);

res.send("Order created successfully!");
} catch (err) {
console.log(err);
res.status(500).send("Error creating order");
}
});

报错信息

TypeError: Cannot read properties of undefined (reading 'productName')

尝试直接查询productID而非productName时,仍出现类似错误,提示无法读取undefined的productID属性。


解决方案

  • 核心原因:productNameResult[0]为undefined,说明数据库中没有匹配selectedProductName的记录,查询返回空数组。
  • 合并查询逻辑:取消两次冗余的产品查询,直接通过selectedProductName获取productID,减少数据库交互:
    // 替换原来的两次产品查询
    const getProductIDQuery = `
      SELECT productID FROM product WHERE productName = ?
    `;
    const productIDResult = await db.query(getProductIDQuery, [selectedProductName]);
    
  • 添加空值校验:在读取查询结果前,先判断是否存在有效记录,避免触发undefined属性读取错误:
    if (!productIDResult || productIDResult.length === 0) {
      return res.status(404).send("对应产品不存在");
    }
    const productID = productIDResult[0].productID;
    
  • 校验数据匹配度:检查selectedProductName的实际值是否和product表中的productName完全一致(注意大小写、空格、特殊字符),可以直接在数据库执行SELECT * FROM product WHERE productName LIKE '%Black Jacket%'验证是否存在匹配记录。
  • 确认前端传参:查看控制台打印的Selected Product Name:值,确认前端传入的参数没有被截断或修改。

内容的提问来源于stack exchange,提问作者Kristian Diaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 16:55:42