Express路由中profile.experience.unshift触发Cannot read properties of undefined错误
问题原因及解决办法
报错原因
出现Cannot read properties of undefined (reading 'unshift')的核心原因是**profile.experience为undefined**,具体分两种场景:
- 数据库中匹配到的
Profile文档未初始化experience字段——比如模型定义时没给该字段设默认空数组,或是新创建的用户profile还未添加过任何经历。 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
相关产品推荐
相关产品推荐

