I am student and learning ReactJS building a Web aplication and I am having problem with that error.
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));
})
});
here is profile model where experience array is declared
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
},
}
],
});
and thats the error I got
(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)
I am using Visual Studio Code on Windows 10 Pro And testing app using Postman Web
profile.experience.unshift(newExp)
this line causes the error (unless it is caused by the code you didn't post).
Possible cause is that your findOne
did not actually "findOne" and returned undefined.
You could add an 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));
})
});
Or any equivalent code.
Parameter profile
is null. You need to pass the object to the resolve
method in the Promise definition, findOne
, (not shown above). Example:
let findOne = new Promise(function(resolve, reject) { let resolveParam = { experience: [] }; setTimeout(() => resolve(resolveParam), 1000); }); findOne.then( profile => console.log(profile) );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.