0

Working on a blog site. In MongoDB my blog posts don't have a comments field to start out. I would like to use $push to add a comments field and add the comment value. The code below doesnt throw any errors, the console.log fires but when I check the fields in MongoDB nothing has changed.

Post.findByIdAndUpdate(
    postid,
    {$push:{"comments": comment}},
    {new: true},
    function(err, added){
        if(err){
            throw err;
        } else {
            console.log('\n-------- Comment Added ----------\n');
            res.redirect('/');
        }
    }
);

EDIT: I figured out that this is because I didn't have a comment field set up in the schema. But now that I added it, how do I deal with the comment field being undefined initially? I have jade code that lists all of the comments if they exist:

if post.comments
        h3 Comments
        each comment, i in comments
            .comment
                p.comment-name #{comment.name}
                p.comment-text #{comment.body}

But I get error:

p.comment-text #{comment.body} Cannot read property 'length' of undefined

2 Answers 2

1

Thanks Mariya! The problem is that you cant push new fields into mongoose models. All fields have to be defined before hand.

Sign up to request clarification or add additional context in comments.

Comments

0

Try with $addToSet instead of $push.

Post.findByIdAndUpdate(
postid,
{$addToSet:{"comments": comment}},
{new: true},
function(err, added){
    if(err){
        throw err;
    } else {
        console.log('\n-------- Comment Added ----------\n');
        res.redirect('/');
    }
});

5 Comments

but theres no array there in the first place
doesnt addtoset just add to an existing array instead of creating a new field?
Thats what i JUST figured out! There was no comment field in the schema :) I just added it but now I have another problem on the Jade page. The Jade page is supposed to show comments for a post IF there are comments. But when there are no comments, it has trouble dealing with it because it is undefined. Can I set it to something other than undefined in the schema?
You defined comment field as array right? So you can check by its length whether it has elements or not
OK got it working by checking length now. The Jade error was a separate issue. The loop should be each comment, i in post.comments

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.