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

Jest中SuperTest执行PUT接口返回旧数据问题求助(MongoDB关联模型)

问题:关联MongoDB ObjectID的模型PUT接口测试异常

普通属性的模型执行PUT操作时完全正常,但在通过MongoDB ObjectID关联其他模型的Solution模型中,PUT接口测试出现异常:数据库里的对象已经成功更新,但SuperTest返回的响应还是原始数据。

测试代码

describe('PUT /:id', () => {
  it('should update a specific solution', async () => {
    const answer = await Answer.findOne({
      content: 'good answer here'
    })
    const solution = await Solution.findOne({
      answer: answer._id
    })
    const codeID = solution.code;
    const answerUP = new mongoose.Types.ObjectId().toString();
    const codeUP = new mongoose.Types.ObjectId().toString();
    const solutionUp = {
      answer: answerUP,
      code: codeUP
    };
    const res = await request(server)
      .put(`${root}/${solution._id}`)
      .send(solutionUp);

    const updated = await Solution.findById(solution._id);
    const revert = await Solution.findByIdAndUpdate(solution._id, {
      answer: answer._id,
      code: codeID
    })
    const reverted = await Solution.findById(solution._id).populate(['answer', 'code']);

    console.log('Updated:', updated);
    console.log('reverted:', reverted);

    expect(res.status).toBe(200);
    expect(res.body).toHaveProperty('answer', answerUP);
    expect(res.body).toHaveProperty('code', codeUP);
  })
})

Jest报错信息

● /solutions › PUT /:id › should update a specific solution

    expect(received).toHaveProperty(path, value)

    Expected path: "answer"

    Expected value: "62fc15ae5f22653969d4d702"
    Received value: "62fc15a51aa9ad1b58f48f4f"

       98 |
       99 |       expect(res.status).toBe(200);
    > 100 |       expect(res.body).toHaveProperty('answer', answerUP);
          |                        ^
      101 |       expect(res.body).toHaveProperty('code', codeUP);
      102 |       // expect(res.body.answer).toEqual(answerUP);
      103 |       // expect(res.body).toHaveProperty('code', codeUP);

      at Object.toHaveProperty (tests/integration/solutions.test.js:100:24)

排查与修复建议

  • 检查接口返回逻辑:大概率是接口更新数据库后,直接返回了更新前查询到的旧文档,没有重新查询最新数据。
  • 修正Mongoose更新方法的返回设置:如果用findByIdAndUpdate,默认返回更新前的文档,必须加{ new: true }选项才能拿到更新后的结果,同时建议加上runValidators: true保证字段校验生效。
  • 关联字段的处理:如果接口需要返回关联的answer或code数据,要在更新完成后再执行populate,不能复用更新前的关联查询结果。

示例修复后的接口核心逻辑:

// 接口中的更新逻辑
const updatedSolution = await Solution.findByIdAndUpdate(
  req.params.id,
  req.body,
  { new: true, runValidators: true } // 关键:new: true 返回更新后的数据
).populate(['answer', 'code']); // 按需关联查询

res.status(200).json(updatedSolution);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:36:21