4

I have documents similar to this document in my mongo db

{
    "_id": ObjectId("5cbf416ec6490b9baff4d284"),
    "rewards" : [ 
        {
            "percent" : NumberLong(100),
            "promotion_id" : "promotest"
        }
    ],
    "eligible_for": ["XYZ","ABC"]

}

When I updated with a proper document then it is updating the document properly

But when I pass rewards, eligible_for as null then eligible_for getting updated to null but rewards not getting updated to null

{
    "rewards" : null,
    "eligible_for": null

}

then the newly updated document

{
    "_id": ObjectId("5cbf416ec6490b9baff4d284"),
    "rewards" : [ 
        {
            "percent" : NumberLong(100),
            "promotion_id" : "promotest"
        }
    ],
    "eligible_for": null

}

This is the query I am using to update the document using mongo-go-driver. r.PollingGameCollection.UpdateOne(ctx, bson.M{"_id": poll.RawId}, M{"$set": poll})

Objects are:

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"`
}
icza
  • 389,944
  • 63
  • 907
  • 827
Srinivas
  • 294
  • 3
  • 18
  • 1
    Your MongoDB Object is not valid JSON. Why are the quotes around eligible_for missing? – jrenk Oct 11 '19 at 11:21
  • What is the value of `poll` in `r.PollingGameCollection.UpdateOne(ctx, bson.M{"_id": poll.RawId}, M{"$set": poll}`? – masnun Oct 11 '19 at 11:57

1 Answers1

5

First: you have an extra space in the bson tag value of PollingGame.EligibleForbson", remove that: bson:"eligible_for, omitempty".

If you remove that space, you'll notice it doesn't even set eligible_for to null anymore.

And the reason is because you use the ,omitempty option. This tells the driver to exclude the field if its value is nil (the zero value). So you want to update, but these fields will not be included in the $set operation, so they won't change.

If you remove the ,omitempty option, it will work:

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"`
}

(Note I also changed objectid.ObjectID to primitive.ObjectID as that is the type you have to use for MongoDB object IDs.)

icza
  • 389,944
  • 63
  • 907
  • 827