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

采用MSC模型时控制器层接收undefined,无法创建产品求助

问题分析与修复方案

核心问题1:日志无法打印、产品无法创建

service层中,当schema.validateName验证通过时,error为null,此时执行console.log(error.type, 'service error')会触发Cannot read properties of null (reading 'type')的报错,直接中断函数执行,导致后续调用model创建产品的逻辑完全无法运行,自然无法创建产品,后续日志也不会打印。

核心问题2:无法获取SQL自增ID

controller层解构错误:service返回的message字段才是model返回的包含id和name的对象,但controller直接从service返回值中解构id和name,这两个属性根本不存在,导致无法拿到自增ID。


修复后的代码

product.model(优化变量名,避免混淆)

const regProduct = async (newProduct) => {
    const [results] = await connection.execute(
      'INSERT INTO StoreManager.products (name) VALUES (?)',
      [newProduct]
    );
    return { id: results.insertId, name: newProduct };
};

product.service(修复日志报错问题,调整逻辑顺序)

const regProduct = async (name) => {
  const error = schema.validateName({ name });
  
  if (error) {
    console.log(error.type, 'service error');
    return error;
  }
  
  const newProduct = await productModel.regProduct(name);
  console.log('待创建产品名称:', name);
  return { type: null, message: newProduct };
};

product.controller(修复解构错误,正确获取ID和名称)

const regProduct = async (req, res) => {
  const { name } = req.body;
  const serviceResult = await productService.regProduct(name);
  
  console.log(serviceResult.message, 'controller message');

  if (serviceResult.type) {
    return res.status(mapError(serviceResult.type)).json({ message: serviceResult.message });
  }

  const { id, name: productName } = serviceResult.message;
  return res.status(201).json({ id, name: productName });
};

内容的提问来源于stack exchange,提问作者Marcel Guimarães

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 15:03:25