1

HI I am using MEAN stack with two data models that are interrelated:

Post and Comment

So in my PostSchema I have

comments:{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Comment'

and in my CommentSchema I have

post:{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Post'
    }

After I input a comment in my view I want the backend to save the comment in the Comment collection and also save the comment in the Post collection.

In my server app.js file:

comment.save(function(err,comment){
        if(err){return next(err);}
        var post = new Post(req.post)
        post.comments.push(comment)
       // OR req.post.comments.push(comment);etc
        post.save(function(err,post){
            if(err){return next(err);}

            res.json(comment);
        })
    })

However, where I use post.comments.push or req.post.comments.push, I get an error message on command line that push is not a function.

The above code is from an online tutorial[1] . I searched the net but cant find any similar example of push being used.

Can you please let me know if I have been misled with push and if there is another way that I should be doing this?

[1]https://thinkster.io/mean-stack-tutorial#wiring-everything-up

1
  • The error means post.comments is not an array. Commented Jun 27, 2016 at 7:03

1 Answer 1

1

It looks like you did not define ARRAY of comments, but only one (standard) comment, therefore it is not array and it does not have "push" method. The definition should look like this :

comments:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Comment'}]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.