You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose推送对象至数组时触发TypeError错误求助

问题解决:Mongoose中无法推送Comment到Post的comments数组

错误根源

你的Post Schema里定义的评论数组字段是**commments(多了一个m)**,但代码里调用的是post.comments,字段名拼写不一致,导致找不到该属性,触发Cannot read properties of undefined (reading 'push')错误。

修复步骤

  1. 修正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
});
  1. 修正业务逻辑代码
    字段名匹配后,原代码的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 01:07:12