登录
首页 >  Golang >  Go问答

更新 MongoDB 驱动程序无法将对象数组设为空

来源:stackoverflow

时间:2024-03-09 17:30:27 461浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《更新 MongoDB 驱动程序无法将对象数组设为空》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我的 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 驱动程序无法将对象数组设为空》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>