0

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:"exam" 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 .

Gopher_k
  • 273
  • 2
  • 9
  • This is unrelated to Go or the mongo-go driver. MongoDB itself does not allow $push-ing into a field having `null` value. See the marked duplicate what to do. – icza Dec 02 '22 at 11:12
  • @icza when i try to insert it writes null instead of empty array , but in mgo driver it used to write as empty array – Gopher_k Dec 02 '22 at 11:16
  • 1
    Set the `Exam` field to an empty slice before insertion if you want it to be an empty array, e.g. `sample.Exam = []Result{}` (this of course only works if you don't use the `,omitempty` BSON tag option). – icza Dec 02 '22 at 11:22
  • @icza is there a way where i can directly handle all these in the $push , Just check if the field is $ifNull then $concatArray ? Or something like $ifNull then initialize an array and append that ? – Gopher_k Dec 02 '22 at 11:41
  • Yes, you can check / handle `$push` into `null` fields, which is exactly what the marked duplicate is about. Have you even checked it? – icza Dec 02 '22 at 11:43
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/250087/discussion-between-karthik-and-icza). – Gopher_k Dec 02 '22 at 11:43
  • @icza that answer was not that helpful . This question will help answer this problem all together https://stackoverflow.com/questions/74653260/how-to-use-mongocompact-package-in-mongoclient-connect-options – Gopher_k Dec 02 '22 at 11:53

1 Answers1

1

I think you can add omitempty to the bson tag. When you're inserting a document and that field has not any element, mongo will not insert anything (I mean there was no field with that name in that document) so when you want to update it ($push), mongo will not find any error on it and you can do it.

type Sample struct {
    Data     string                   `bson:"data,omitempty" json:"data,omitempty" valid:"-"`
    Exam     []Result                 `bson:"exam,omitempty" json:"data,omitempty" valid:"-"`
}
ttrasn
  • 4,322
  • 4
  • 26
  • 43