How to $push a nil slice in golang

After the code migration from mgo to go-mongo driver the []model are getting updated with null instead of empty array , So i’m not able to do $push operation for a golang struct . How to $push even if the array is null is there a way ?


type Sample struct {
	Data     string                   `json:"data,omitempty" valid:"-"`
	Exam    []Result                `json:"result" valid:"-"`
}

type Result struct {

	field1          string `json:"field1,omitempty"`
	field2          string `json:"field2,omitempty"`

}

//what I try to do

var result m.Result  
err := db.sampleCollection.UpdateOne(bson.M{"id": sampleID}, bson.M{"$push": bson.M{"exam": result}})

But during insert the field result is set to null instead of empty [] array , So it’s not allowing to do a $push operation . Since that’s not an array and just an object, In the old mgo driver it used to work fine because it was never set to null .

1 Like

You can avoid this issue by inserting the line below before calling UpdateOne method:

result.Exams = []Exam{}