我正在尝试使用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
答案 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"
}