Hi, so in general I have an iterating problem:
// @route POST api/profile/rating/:id
// @description Add rating
// @access Private
router.post(
"/rating/:id",
passport.authenticate("jwt", { session: false }),
(req, res) => {
console.log("Profile ID that we are rating", req.body.profileId);
Profile.findById(req.body.profileId)
.then(profile => {
console.log("All in the profile ratings", profile.ratings);
if (
profile.ratings.filter(
rating => rating.user.toString() === req.user.id
).length > 0
) {
return res
.status(400)
.json({ alreadyrated: "User already rated this profile" });
}
profile.ratings.unshift(
{ user: req.user.id },
{ ratingNumber: req.body.ratingNumber }
);
profile.save().then(profile => res.json(profile));
})
.catch(err => {
res.status(404).json({ profilenotfound: "No profile found" });
});
}
);
This is the console.log I get:
All in the profile ratings CoreMongooseArray [
[0] { _id: 5c7d46893a028e1dec3e3f0e,
[0] user: 5c7d3e1618874a2540350d20 },
[0] { _id: 5c7d46893a028e1dec3e3f0f, ratingNumber: 5 } ]
And the error is: { profilenotfound: "No profile found" }
So the problem is that this code worked when I didn't have another element (this ratingNumber and his ID), but now when I have it when I want to compare if the id of the person that is rating already exists I get an error since I cannot correctly check it.
Ankit Parashar
Hustler
Since it is showing "No profile found", it means it going into catch error block, and error is originating where you are comparing rating.user.toString() and req.user.id, because you are not having null check on rating.user, instead use, this:
rating.user && rating.user.toString() === req.user.id