0

我正在尝试使用库UpdateOnemongo-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
4

1 回答 1

0

至少根据本教程,您需要传递 abson.D作为 的第三个参数。UpdateOne

因此,在您的代码中,您不应该传递d,而是传递updUpdateOne函数:

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"
}
于 2019-08-22T16:59:45.813 回答