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

Mongoose更新answers子数组时报findByIdAndUpdate未定义错误如何解决

错误原因

  1. 后端报错核心原因:question.answers是数组类型,不存在answer属性,question.answers.answer取值为undefined,调用findByIdAndUpdate自然抛出类型错误。
  2. 子文档数组没有直接调用findByIdAndUpdate的方法,需要使用MongoDB的数组定位符完成嵌套更新,或者先遍历数组找到对应子文档再修改。
  3. 前端代码也存在逻辑问题:若ques是单个问题对象而非数组,调用map方法会报错,且原匹配逻辑无法正确定位到要更新的回答。

修复方案

后端代码修复

推荐直接使用原子更新操作,无需先查询再修改,性能更高:

router.put('/answer/like',authenticate,(req,res)=>{
    const { quesId, ansId } = req.body
    Question.findOneAndUpdate(
        // 匹配对应问题和对应回答
        { _id: quesId, "answers._id": ansId },
        // 用$定位符定位到匹配的回答,添加点赞ID
        { $push: { "answers.$.likes": req.rootUser._id } },
        { new: true }
    ).exec((err, updatedQues) => {
        if(err){
            return res.status(422).json({error: err})
        }
        // 返回更新后的回答给前端
        const targetAns = updatedQues.answers.find(ans => ans._id.toString() === ansId.toString())
        res.json(targetAns)
    })
})

前端代码修复

修正数组遍历和状态更新逻辑:

const likePost = (id)=>{
    fetch('/answer/like',{
        method:"put",
        headers:{
            Accept:"application/json",
            "Content-Type":"application/json",
        },
        body:JSON.stringify({
            quesId: ques._id,
            ansId: id
        })
    }).then(res=>res.json())
    .then(result=>{
        // 更新当前问题下的answers数组
        const newAnswers = ques.answers.map(ans => {
            if(ans._id.toString() === result._id.toString()){
                return result
            }
            return ans
        })
        setQues({...ques, answers: newAnswers})
    }).catch(err=>{
        console.log(err)
    })
}

注意事项

确保Mongoose为answers子文档自动生成了_id字段,默认配置下会自动生成,若手动关闭了该配置需要重新开启,否则无法通过ansId匹配到对应回答。

内容的提问来源于stack exchange,提问作者Prateek Nandle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:36:03