Mongoose推送对象至数组时触发TypeError错误求助
问题解决:Mongoose中无法推送Comment到Post的comments数组
错误根源
你的Post Schema里定义的评论数组字段是**commments(多了一个m)**,但代码里调用的是post.comments,字段名拼写不一致,导致找不到该属性,触发Cannot read properties of undefined (reading 'push')错误。
修复步骤
- 修正Schema字段名
把Post Schema里的commments改为comments,确保和代码中的调用匹配,同时修正ref指向(应该关联Comment模型而非Post):
const postSchema = new mongoose.Schema({ content:{ type: String, required: true, }, user:{ type:mongoose.Schema.Types.ObjectId, ref:'User' }, // 修正字段名:commments → comments,同时修正ref指向 comments: [ { type:mongoose.Schema.Types.ObjectId, ref:'Comment' }, ], }, { timestamps:true });
- 修正业务逻辑代码
字段名匹配后,原代码的post.comments.push(comment)即可正常执行。另外推荐用更高效的方式,直接通过findByIdAndUpdate更新帖子,减少一次数据库查询:
// 先创建评论,再更新对应帖子的comments数组 Comment.create({ content: req.body.content, post: req.body.post, user: req.user._id }, function(err, comment){ if(err){ console.log(err); return res.redirect('/'); } // 直接推送评论ID到帖子的comments数组 Post.findByIdAndUpdate( req.body.post, { $push: { comments: comment._id } }, { new: true }, function(err){ if(err){ console.log(err); } res.redirect('/'); } ); });
额外提示
- 建议用
async/await替代嵌套回调,代码更易维护:
try { const comment = await Comment.create({ content: req.body.content, post: req.body.post, user: req.user._id }); await Post.findByIdAndUpdate(req.body.post, { $push: { comments: comment._id } }); res.redirect('/'); } catch(err) { console.log(err); res.redirect('/'); }
- 确保Comment模型的Schema正确关联Post:
const commentSchema = new mongoose.Schema({ content: String, post: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' }, user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } }, { timestamps: true });
内容的提问来源于stack exchange,提问作者yash bhardwaj
相关产品推荐
相关产品推荐

