Node.js报错Cannot read property 'push' of undefined 无法向MongoDB帖子推送评论
报错原因
触发TypeError: Cannot read property 'push' of undefined的核心原因是Post模型的Schema中没有定义comments字段,你查询返回的post文档对象本身不存在comments属性,调用push方法自然会报错。你仅在Comment的Schema中定义了关联Post的字段,没有在Post的Schema中做反向关联、存储评论ID的数组字段。
解决方案
第一步:修改Post模型的Schema定义,新增comments数组字段
找到你的Post模型对应的Schema代码,新增comments字段,类型为ObjectId数组,关联Comment模型即可:
const mongoose = require('mongoose') const postSchema = new mongoose.Schema({ // 保留你原本定义的Post字段,比如标题、内容、关联用户等 title: String, content: String, user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, // 新增comments字段 comments: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Comment', default: [] // 加默认值可以避免旧数据没有该字段的问题 } ] },{ timestamps: true }) const Post = mongoose.model('Post' , postSchema) module.exports = Post
第二步:优化控制器代码的错误处理逻辑
你当前的代码缺少异常判断,异步操作出错时仍会执行后续逻辑,建议补充错误捕获:
const Comment = require('../models/comment') const Post = require('../models/post') module.exports.create = function(req,res){ Post.findById(req.body.post, function(err ,post){ if(err){ console.log("查询帖子出错:", err) return res.redirect('/') } if(post){ Comment.create({ content: req.body.content, post: req.body.post, user: req.body._id },function(err, comment){ if(err){ console.log("创建评论出错:", err) return res.redirect('/') } post.comments.push(comment._id) // 仅存储评论ID即可,不需要存完整评论对象 post.save(function(err){ if(err){ console.log("保存帖子评论关联出错:", err) } return res.redirect('/') }) }) }else{ return res.redirect('/') } }) }
补充说明
如果之前已经生成过Post集合的旧数据,这些旧文档默认没有comments字段,你可以手动给旧数据补上空数组值,或者直接使用上面Schema里给出的default: []配置,即可避免旧数据触发同样的报错。后续查询帖子需要带出评论内容时,调用populate('comments')方法即可拿到完整的评论数据。
内容的提问来源于stack exchange,提问作者krishna
相关产品推荐
相关产品推荐

