0

Please look at this code:

// Update route
router.put("/:comment_id", function (req, res) {
    Campground.findOneAndUpdate(
        {"_id": req.params.id, "comments._id": req.params.comment_id },
        {"$set": {"comments.$.text": req.body.comment.text}},
        function (err, campground) {
            if (err) {
                console.log("campground: " + campground); //logs campground: undefined
                console.log("comment id: " + req.params.comment_id); // logs comment id: 5a5f2ab0a6dccd210c0136de
                console.log("campground id: " + req.params.id); // logs campground id: 5a5e083af62da603900ab0d4
                res.redirect("/campgrounds");
            } else {
                res.redirect("/campgrounds/" + campground._id);
            }
        }
    );
});

the ids refers to an url like this:

http://localhost:4000/campgrounds/5a5e083af62da603900ab0d4/comments/5a5e0845f62da603900ab0d5/edit

This is weird for me, why I cannot reach campground? In this way i cannot update the doc I need. Please help me to find a solution.

EDIT: Error provided by console.log(err); :

{ CastError: Cast to ObjectId failed for value "secondo me no" at path "comments"
    at new CastError (folder\node_modules\mongoose\lib\error\cast.js:27:11)
    at ObjectId.cast (folder\node_modules\mongoose\lib\schema\objectid.js:158:13)
    at ObjectId.SchemaType.applySetters (folder\node_modules\mongoose\lib\schematype.js:695:12)
    at ObjectId.SchemaType._castForQuery (folder\node_modules\mongoose\lib\schematype.js:1066:15)
    at ObjectId.castForQuery (folder\node_modules\mongoose\lib\schema\objectid.js:198:15)
    at ObjectId.SchemaType.castForQueryWrapper (folder\node_modules\mongoose\lib\schematype.js:1035:15)
    at castUpdateVal (folder\node_modules\mongoose\lib\services\query\castUpdate.js:345:19)
    at walkUpdatePath (folder\node_modules\mongoose\lib\services\query\castUpdate.js:229:22)
    at castUpdate (folder\node_modules\mongoose\lib\services\query\castUpdate.js:72:18)
    at model.Query._castUpdate (folder\node_modules\mongoose\lib\query.js:2991:10)
    at castDoc (folder\node_modules\mongoose\lib\query.js:3017:18)
    at model.Query.Query._findAndModify (folder\node_modules\mongoose\lib\query.js:2292:19)
    at model.Query.Query._findOneAndUpdate (folder\node_modules\mongoose\lib\query.js:2139:8)
    at folder\node_modules\kareem\index.js:276:8
    at folder\node_modules\kareem\index.js:23:7
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
  message: 'Cast to ObjectId failed for value "secondo me no" at path "comments"',
  name: 'CastError',
  stringValue: '"secondo me no"',
  kind: 'ObjectId',
  value: 'secondo me no',
  path: 'comments',
  reason: undefined }

@Younel this is the Edit view:

<% include ../partials/header %>
<div class="container">
    <div class="row">
        <h1 style="text-align: center;">Edit Comment</h1>
        <div style="width: 30%; margin:25px auto;">
            <form action="/campgrounds/<%= campground_id %>/comments/<%= comment._id %>?_method=PUT" method="POST">
                <div class="form-group">
                    <input class="form-control" type="text" name="comment[text]" value="<%= comment.text %>">
                </div>
                <div class="form-group">
                    <button class="btn btn-lg btn-primary btn-block">Submit!</button>
                </div>
            </form>
            <a href="/campgrounds">Go Back</a>
        </div>
    </div>
</div>
<% include ../partials/footer %>

"secondo me no" is the comment[text] value

This is a github repo: https://github.com/ufollettu/YelpCamp.git (run v10/app.js)

15
  • And what about console.log(err) ? You know there's an error, but you're not even logging it. Commented Jan 17, 2018 at 12:34
  • you sure req.params.id is set as expected? It seems your program gets the comment id properly, but fails to find the Campground, which suggests the Campground id is not being properly passed to the mongoose model. Commented Jan 17, 2018 at 12:37
  • @Jeremy: I make an Edit, please see the Question above Commented Jan 17, 2018 at 12:41
  • @Sergeon I think yes: I use var commentsRoutes = require("./routes/comments") and app.use("/campgrounds/:id/comments", commentsRoutes); in my app Commented Jan 17, 2018 at 12:43
  • Ah, so it's not undefined error. It's clearly Cast to ObjectId failed. Apparently it's getting passed "secondo me no" as an _id Commented Jan 17, 2018 at 12:44

1 Answer 1

1

If I get your models right, comments is not just an array but an array of embedded documents, so the update must be something like this:

Campground.findById(req.params.id, function(err, doc) {
    if (err || !doc) {
        ...
    }
    const comment = doc.comments.id(req.params.comment_id);
    if (!comment) {
        ...
    }
    comment.text = req.body.comment.text;
    doc.save(function (err) {
        if (err) {
            ...
        }
    })
})

For referenced documents:

router.put("/:comment_id", function (req, res) {
    Comment.findOneAndUpdate(
        {"_id": req.params.comment_id},
        {"$set": {"text": req.body.comment.text}},
        function (err, comment) {
            if (err) {
                ...
            } 
            res.redirect("/campgrounds/" + req.params.id);
        }
    );
}); 
Sign up to request clarification or add additional context in comments.

4 Comments

Console says TypeError: doc.comments.id is not a function
Yeah, my bad. Comments in campgroundSchema should be [commentSchema] - the thing you commented off there.
There's no way with Referenced Docs instead of Embedded ones?
Referenced docs are stored in a separate collection. If it is what you intend to use, you will need to update the comment document in its own collection without even touching Campground.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.