在mongo-go-driver

时间:2019-08-22 15:08:48

标签: mongodb go bson mongo-go

我正在尝试使用UpdateOne库中的mongo-go-driver,但是此方法使用bson文档。我给它一个接口参数(json)。

我的问题是找到解析我的json请求到bson以便动态更新字段的最佳方法。谢谢。

func (s Store) Update(id`enter code here` bson.D, d interface{}) (*mongo.UpdateResult, int32, string) {
    upd := bson.D{
        {
            "$inc", bson.D{
                d,
            },
        },
    }
    c, ctx, _ := getCollection(s.conn, s.dbName, s.collectionName)
    res, err := c.UpdateOne(ctx, id, d)
    if err != nil {
        log.Fatal(err)
        return res, 500, "DATABASE ERROR: Cannot update document"
    }
    return res, 200, "none"
}

我收到此错误:

Error: cannot use d (type inte`enter code here`rface {}) as type primitive.E in array or slice literal: need type assertion

1 个答案:

答案 0 :(得分:0)

至少根据this tutorial,您需要传递bson.D作为UpdateOne的第三个参数。

因此,在您的代码中,您不应传递d,而应将upd传递给UpdateOne函数:

func (s Store) Update(id`enter code here` bson.D, d interface{}) (*mongo.UpdateResult, int32, string) {
    upd := bson.D{
        {
            "$inc", bson.D{
                d,
            },
        },
    }
    c, ctx, _ := getCollection(s.conn, s.dbName, s.collectionName)
    res, err := c.UpdateOne(ctx, id, upd)
    if err != nil {
        log.Fatal(err)
        return res, 500, "DATABASE ERROR: Cannot update document"
    }
    return res, 200, "none"
}