Search code examples
node.jsmongodbmongoosepushmongoose-schema

"TypeError: Cannot read property 'push' of undefined" while using mongoose ODM


Below is the snippet of my code where I am getting the above mentioned error. Basically I want to find topic in my collection using the id and then pushing the comment onto it (array). I have used mongoose model in my project.

Topic.findById(id)
  .then((result) => {
    console.log(result);
    topic = result,
    topic.comments.push(comm);
    topic.save()
    .then((result) => {
        res.redirect("/topics/:id");
    })
    .catch((err) => {
        console.log(err);
    });
  })

I have also tried other options which is I think is more incorrect. I will be writing them in comments if it helps. :)


Solution

  • In the my TopicSchema, I just initiated the comments array like below and it worked!

    comments: {
        type: Array,
        required: false
    }