我是一名学生,正在学习ReactJS构建网络应用程序,我遇到了这个错误的问题。
router.post('/experience', passport.authenticate('jwt', { session: false }), (req, res) => {
const { errors, isValid } = validateExperienceInput(req.body);
//Check Validation
if (!isValid) {
//Return any errors with 400 status
return res.status(400).json(errors);
}
Profile.findOne({ user: req.user_id })
.then(profile => {
const newExp = {
title: req.body.title,
company: req.body.company,
}
//Add to experience array
//There is the error generated
profile.experience.unshift(newExp);
profile.save().then(profile => res.json(profile));
})
});下面是一个配置文件模型,其中声明了经验数组
const ProfileSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
handle: {
type: String,
required: true,
max: 40
},
experience: [
{
title: {
type: String,
required: true
},
company: {
type: String,
required: true
},
}
],
});这就是我得到的错误
(node:14580) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'experience' of null
at C:\Users\HP 840 G3\Desktop\LinkedIn\routes\api\profile.js:180:21
at processTicksAndRejections (internal/process/task_queues.js:93:5)我在Windows 10专业版上使用Visual Studio代码,并使用Postman Web测试应用程序
发布于 2021-04-16 17:27:49
profile.experience.unshift(newExp)此行将导致错误(除非它是由您没有发布的代码引起的)。
可能的原因是您的findOne实际上没有"findOne“并且返回了undefined。
您可以添加一个if
Profile.findOne({ user: req.user_id })
.then(profile => {
if (!profile) return
const newExp = {
title: req.body.title,
company: req.body.company,
}
//Add to experience array
//There is the error generated
profile.experience.unshift(newExp);
profile.save().then(profile => res.json(profile));
})
});或任何等效的代码。
发布于 2021-04-16 17:27:53
参数profile为null。您需要将对象传递给Promise定义findOne中的resolve方法(上面没有显示)。示例:
let findOne = new Promise(function(resolve, reject) {
let resolveParam = { experience: [] };
setTimeout(() => resolve(resolveParam), 1000);
});
findOne.then(
profile => console.log(profile)
);
https://stackoverflow.com/questions/67122328
复制相似问题