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

Mongoose无法向数组插入对象:push添加评论不生效且无报错

问题原因及修复方案

1. findOneAndUpdate参数顺序错误

mongoose的findOneAndUpdate方法参数顺序为查询条件、更新操作、配置项、回调,你的代码里把{new: true}配置项放到了第二个参数(更新操作)的位置,导致更新语句完全没有执行,这是评论没有插入的核心原因。

2. 评论对象字段与Schema定义不匹配

你的Schema中comments子文档定义的字段为date、user、text,但你构造的commentObj字段为date、userId、text,字段名userId和Schema要求的user不一致,且Schema中date字段声明为String类型,你传入的是Date对象,类型不匹配会被Mongoose静默丢弃。

3. $push操作多嵌套了一层对象

你写的{$push: {comments: { commentObj }}}相当于往comments数组中插入{commentObj: 你的评论对象}的结构,和Schema要求的子文档结构不符,应该直接传入commentObj本身即可。

4. 错误捕获逻辑缺失

你同时混用了await和回调函数,且catch块为空,即使更新过程中抛出错误也不会打印,导致你看不到任何错误提示。

修复后的代码示例

首先可对Schema做可选优化,将date类型改为Date更符合业务场景:

comments: [
  {
    date: {
      type: Date,
      required: true,
    },
    user: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      required: true,
    },
    text: {
      type: String,
      required: true,
    },
  }
]

路由代码修复如下:

export const createComment = async (req: Request, res: Response) => {
  try {
    const postId = req.params.postId;
    const userId = req.params.userId;
    const comment = req.body.comment;
    const commentObj = {
      date: new Date(), // 如果Schema保留String类型,这里改成new Date().toISOString()即可
      user: userId, // 字段名改为Schema要求的user
      text: comment
    };
    // 调整参数顺序,优先用await写法,不需要混用回调
    const updatedPost = await Post.findOneAndUpdate(
      { _id: postId }, 
      {$push: { comments: commentObj }}, // 直接传入commentObj,不要多套一层
      { new: true } // 配置项放到第三个参数位置
    );
    return res.status(200).send(updatedPost);
  } catch (error) {
    // 打印错误方便排查
    console.log("更新失败:", error);
    return res.status(500).send({msg: "评论添加失败"});
  }
}

内容的提问来源于stack exchange,提问作者EDGAR MEDINA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:06:03