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

MERN栈如何发送POST请求操作数组指定字段?answers数组加数据失败怎么解决

问题原因与正确实现

错误根源

  • answers是Schema中定义的对象数组类型,你直接操作question.answers.answer属于访问数组本身的answer属性,这个属性根本不存在,自然无法写入数据
  • 你之前尝试的question.answers.answer.push()写法层级错误,push方法应该调用在answers数组本身上,传入完整的符合answers子结构的对象

基础版正确实现(基于你原有写法修改)

router.post('/answer/:id',authenticate,(req,res)=>{
    const { answer, picofa } = req.body
    Question.findById(req.params.id).then(question=>{
        if(!question) return res.status(404).json({error:"对应问题不存在"})
        // 构造符合子Schema要求的新答案对象
        const newAnswer = {
            answer: answer,
            picofa: picofa || "no photo",
            postedBy: req.user._id // 你的authenticate中间件需提前将登录用户信息挂载到req.user上
        }
        // 将新答案推入answers数组
        question.answers.push(newAnswer)
        question.save().then(result=>{
            res.json(result)
        }).catch(err=>{
            res.status(400).send(err);
        })
    }).catch(err=>{
        res.status(500).send(err);
    })
})

推荐版原子更新实现

无需先查询再保存,直接调用MongoDB原子操作性能更高,避免并发写入冲突:

router.post('/answer/:id',authenticate,(req,res)=>{
    const { answer, picofa } = req.body
    Question.findByIdAndUpdate(
        req.params.id,
        // $push操作符直接向数组插入元素
        {
            $push: {
                answers: {
                    answer: answer,
                    picofa: picofa,
                    postedBy: req.user._id
                }
            }
        },
        // new参数返回更新后的数据,runValidators开启Schema字段校验
        { new: true, runValidators: true }
    ).then(updatedQuestion=>{
        if(!updatedQuestion) return res.status(404).json({error:"对应问题不存在"})
        res.json(updatedQuestion)
    }).catch(err=>{
        res.status(400).send(err)
    })
})

注意事项

如果不需要上传回答配图,可以省略picofa字段,Schema配置的默认值会自动生效。

内容的提问来源于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.29 11:15:02