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

Express路由中profile.experience.unshift触发Cannot read properties of undefined错误

问题原因及解决办法

报错原因

出现Cannot read properties of undefined (reading 'unshift')的核心原因是**profile.experience为undefined**,具体分两种场景:

  1. 数据库中匹配到的Profile文档未初始化experience字段——比如模型定义时没给该字段设默认空数组,或是新创建的用户profile还未添加过任何经历。
  2. Profile.findOne({ user: req.user.id })未找到匹配的profile文档,此时profile为null,访问profile.experience自然会抛出未定义错误。

解决办法

1. 先校验profile是否存在

在操作profile.experience前,先判断查询结果是否存在,不存在则返回404提示:

try {
    const profile = await Profile.findOne({ user: req.user.id });

    // 新增:判断profile是否存在
    if (!profile) {
        return res.status(404).json({ msg: 'Profile not found' });
    }

    // ...后续操作
}

2. 确保experience字段是数组

如果profile存在但experience未定义,先初始化它为空数组,再执行unshift:

// 替换原有的profile.experience.unshift(newExp)代码
if (!profile.experience) {
    profile.experience = [];
}
profile.experience.unshift(newExp);

3. (可选)从根源避免问题:修改Profile模型定义

在Profile模型中给experience字段设置默认空数组,从根源避免未初始化的情况:

// 示例Profile模型代码
const ProfileSchema = new mongoose.Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'user'
    },
    // 其他字段...
    experience: [
        {
            title: { type: String, required: true },
            company: { type: String, required: true },
            // 其他经历字段...
        }
    ],
    // 设置默认值
    default: {
        experience: []
    }
});

修改后的完整路由代码

router.put('/experience', 
    [
        auth, 
        [
          check('title', 'Title is required')
            .not()
            .isEmpty(),
          check('company', 'Company is required')
            .not()
            .isEmpty(),
          check('from', 'From date is required')
            .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 });

            if (!profile) {
                return res.status(404).json({ msg: 'Profile not found' });
            }

            // 初始化experience数组(如果不存在)
            if (!profile.experience) {
                profile.experience = [];
            }

            profile.experience.unshift(newExp);

            await profile.save();

            res.json(profile);

        } catch(err) {
            console.log(err.message);
            res.status(500).send('Server Error ' + err.message);
        }
    }
);

内容的提问来源于stack exchange,提问作者Atmagyan Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 20:09:30