1
votes

This is my code:

app.post("/blogs/:id/comments", function (req, res) {
    blog.findById(req.params.id, function (err, finded) {
        if (err) {
            console.log(finded)
            console.log(err);
            console.log("finded data")
            res.redirect("/blogs");
        } else {
            Comment.create(req.body.comment, function (err, comment) {
                if (err) {
                    console.log(comment)
                    console.log(err);
                    console.log("my coomeent")


                } else {
                    finded.comments.push(comment);
                    finded.save();
                    res.redirect("/blogs/" + finded._id);
                }
            })
        }
    })
});

When i am trying to insert comment second time code gives the following error:

.(node:6064) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ValidationError: blog validation failed: comments: Cast to [undefined] failed for value "[{"_id":"5a7dee043918a20128a1e39e","text":"hey","author":"himansu","__v":0}]" at path "comments" (node:6064) [DEP0018] DeprecationWarning: Unhandled promise rejections are depre cated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

1

1 Answers

1
votes

Himansu,I think method finded.comments.push(comment); returning a promise. So you have to handle the promise. like:

finded.comments.push(comment)
.then(result => {
    finded.save();
    res.redirect("/blogs/" + finded._id);
})
.catch(err => {
    console.log(err);
})