Home > Software design >  bson cannot Decode to nil value with bson:"omitempty" struct tag
bson cannot Decode to nil value with bson:"omitempty" struct tag

Time:06-28

I have a struct:

type User struct {
    ID        primitive.ObjectID `json:"id" bson:"_id,omitempty"`
    Username  *string            `json:"username" bson:"username,omitempty"`
    FirstName *string            `json:"firstName" bson:"first_name,omitempty"`
    LastName  *string            `json:"lastName" bson:"last_name,omitempty"`
    Email     *string            `json:"email" bson:"email,omitempty"`
    GoogleID  *string            `json:"googleID" bson:"google_id,omitempty"`
    PageURLs  []string           `json:"pageURLs" bson:"pages"`
    Schema    int                `json:"-" bson:"schema"` // omitted from graphql
}

I'm calling this code:

updateOption := options.FindOneAndUpdate().SetUpsert(true)

updateData := bson.M{"$set": *user}

filter := bson.M{"google_id": user.GoogleID}

// updated user will have Id
err = findOneUserAndUpdate(context.TODO(), filter, updateData, updateOption).Decode(updatedUser)

With the following user:

var testFirstname = "first"
var testLastname = "last"
var testEmail = "[email protected]"
var testGoogleID = "abc123"
testUser = &model.User{
    FirstName: &testFirstname,
    LastName:  &testLastname,
    Email:     &testEmail,
    GoogleID:  &testGoogleID,
    PageURLs:  []string{},
    Schema:    1,
}

but I'm getting this error saying: cannot Decode to nil value. This is probably because a pointer is nil, but the omitempty build tag should just omit the field in that case. Why would it fail to do so?

CodePudding user response:

updatedUser is what cannot be nil, you need to give it an empty struct at least to decode into.

CodePudding user response:

Seems like updateData := bson.M{"$set": *user} is not valid string. You can try updateData := bson.M{"$set": &user} that seems to work.

  •  Tags:  
  • go
  • Related