首页 > 解决方案 > “TypeError:使用 mongoose ODM 时无法读取未定义的属性‘push’”

问题描述

下面是我收到上述错误的代码片段。基本上我想使用 id 在我的集合中找到主题,然后将评论推送到它(数组)。我在我的项目中使用了猫鼬模型。

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);
    });
  })

我还尝试了其他我认为更不正确的选项。如果有帮助,我会将它们写在评论中。:)

标签: node.jsmongodbmongoosepushmongoose-schema

解决方案


在我的 TopicSchema 中,我刚刚启动了下面的评论数组,它起作用了!

comments: {
    type: Array,
    required: false
}

推荐阅读