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

跟随Udemy课程开发添加Profile经验接口时遇服务器错误求助

问题解决:添加用户经验时出现"Cannot read properties of null (reading 'experience')"错误

错误原因

在PUT api/profile/experience路由中,代码直接尝试访问profile.experience.unshift(newExp),但如果当前用户还未创建个人Profile,Profile.findOne({ user: req.user.id })会返回null,此时访问null的experience属性就会触发该错误。另外,创建/更新Profile的POST路由里还存在一个赋值错误:将status字段错误设置为company的值。

修复方案

1. 修复添加经验的路由

在获取profile后,先判断是否存在,不存在则返回错误提示:

// @route    PUT api/profile/experience
// @desc     Add profile experience
// @access   Private
router.put(
  '/experience',
  [
    auth,
    [
      check('title', 'Title is required field').not().isEmpty(),
      check('company', 'Company is required field').not().isEmpty(),
      check('from', 'From date is required field').not().isEmpty(),
    ],
  ],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    const {
      title,
      company,
      location,
      from,
      to,
      current,
      description,
    } = req.body;

    const newExp = {
      title,
      company,
      location,
      from,
      to,
      current,
      description,
    };
    try {
      const profile = await Profile.findOne({ user: req.user.id });
      // 新增:检查profile是否存在
      if (!profile) {
        return res.status(400).json({ msg: "请先创建个人Profile" });
      }
      profile.experience.unshift(newExp);
      await profile.save();
      res.json(profile);
    } catch (err) {
      console.error(err.message);
      res.status(500).send('Server Error');
    }
  });

2. 修复创建/更新Profile的赋值错误

在POST /api/profile路由中,将profileFields.status = company改为profileFields.status = status:

// 原错误代码
if (status) profileFields.status = company;
// 修改后
if (status) profileFields.status = status;

额外注意

要确保用户在调用添加经验接口前,已经通过POST /api/profile接口创建了自己的Profile,否则会触发Profile不存在的错误提示。


内容的提问来源于stack exchange,提问作者Arshad hossain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 10:24:08