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

使用Go mongo-driver mtest包测试MongoDB CountDocuments遇错求助

解决mtest模拟MongoDB CountDocuments响应的"no 'n' field"错误

你遇到的问题根源在于:CountDocuments对应的是MongoDB的countDocuments命令,不是游标查询,所以不能用mtest.CreateCursorResponse构造响应,需要用mtest.CreateCommandResponse来模拟命令的返回结果。

你的代码里用CreateCursorResponse构造了带嵌套n字段的响应,但驱动期望的是一个直接包含顶级n字段的命令返回文档,且n的类型是数值(不是嵌套的bson.D)。

正确的测试代码写法

func Test_Case(t *testing.T) {
    // DbInit before 
    ...
    mt := mtest.New(t, mtest.NewOptions().ClientType(mtest.Mock))
    defer mt.Close()

    mt.Run(mt.Name(), func(mt *mtest.T) {
        itemId := "item-id-to-count"

        // 用CreateCommandResponse模拟countDocuments命令的返回
        mt.AddMockResponses(mtest.CreateCommandResponse(bson.D{
            {Key: "n", Value: 123}, // 直接设置数值类型的n,对应匹配到的文档数量
            {Key: "ok", Value: 1},  // 必须包含ok字段表示命令执行成功
        }))

        memberCount, err := dbCollection.CountDocuments(context.TODO(), bson.M{"_id": itemId})
        if err != nil {
            mt.Error("did not expect an error, got: ", err)
        }
        
        // 可添加断言验证结果
        if memberCount != 123 {
            mt.Errorf("expected count 123, got %d", memberCount)
        }
    })
}

关键说明

  • countDocuments是数据库命令,驱动会发送该命令并解析返回的n字段值,因此必须用CreateCommandResponse构造响应
  • 返回文档必须包含ok:1字段表示命令执行成功,同时顶级n字段为数值类型,代表匹配到的文档总数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 04:01:55