Leo Fabrikant
Leo Fabrikant

Reputation: 735

$push not creating new array field. Using Mongoose

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

Upvotes: 0

Views: 574

Answers (2)

Leo Fabrikant
Leo Fabrikant

Reputation: 735

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

Upvotes: 1

Mariya James
Mariya James

Reputation: 985

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('/');
    }
});

Upvotes: 0

Related Questions