我的 mongo 数据库中有与此文档类似的文档
{
"_id": ObjectId("5cbf416ec6490b9baff4d284"),
"rewards" : [
{
"percent" : NumberLong(100),
"promotion_id" : "promotest"
}
],
"eligible_for": ["XYZ","ABC"]
}
当我使用正确的文档更新时,它就会正确更新文档
但是当我传递奖励时,eligible_for为null,然后elied_for更新为null,但奖励未更新为null
{
"rewards" : null,
"eligible_for": null
}
然后是新更新的文档
{
"_id": ObjectId("5cbf416ec6490b9baff4d284"),
"rewards" : [
{
"percent" : NumberLong(100),
"promotion_id" : "promotest"
}
],
"eligible_for": null
}
这是我用来使用 mongo-go-driver 更新文档的查询。
r.PollingGameCollection.UpdateOne(ctx, bson.M{"_id": poll.RawId}, M{"$set": poll})
对象是:
type PollingGame struct {
RawId *objectid.ObjectID `json:"-" bson:"_id,omitempty"`
Rewards *[]Reward `json:"rewards,omitempty" bson:"rewards,omitempty"`
EligibleFor []string `json:"eligible_for,omitempty" bson:"eligible_for, omitempty"`
}
type Reward struct {
Percent int `json:"percent,omitempty" bson:"percent,omitempty"`
PromotionId string `json:"promotion_id,omitempty" bson:"promotion_id,omitempty"`
}
最佳答案
首先:PollingGame.EligibleForbson"
的 bson
标记值中有多余的空格,请将其删除:bson:"eligible_for, omitempty"
.
如果删除该空格,您会发现它甚至不再将 eligible_for
设置为 null
。
原因是因为您使用了 ,omitempty
选项。这告诉驱动程序排除该字段(如果该字段的值为nil
)(零值)。所以你想更新,但是这些字段不会被包含在$set
操作中,所以它们不会改变。
如果删除 ,omitempty
选项,它将起作用:
type PollingGame struct {
RawId *primitive.ObjectID `json:"-" bson:"_id,omitempty"`
Rewards *[]Reward `json:"rewards,omitempty" bson:"rewards"`
EligibleFor []string `json:"eligible_for,omitempty" bson:"eligible_for"`
}
(注意,我还将 objectid.ObjectID
更改为 primitive.ObjectID
,因为这是您必须用于 MongoDB 对象 ID 的类型。)
关于mongodb - go mongo 驱动程序更新无法将对象数组设置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58340098/