Search code examples
gobsonmongo-go

Failed to decode camelcase fields using mongo-go-driver


I'm using a struct like so

type User struct {
    Username  string    `json: "username" bson: "username"`
    FirstName string    `json: "firstName" bson: "firstName"`
    LastName  string    `json: "lastName" bson: "lastName"`
    Email     string    `json: "email" bson: "email"`
    Gender    string    `json: "gender" bson: "gender"`
    Password  string    `json: "password" bson: "password"`
    Enabled   bool      `json: "enabled" bson: "enabled"`
    BirthDate time.Time `json: "birthDate" bson: "birthDate"`
    CreatedAt time.Time `json: "createdAt" bson: "createdAt"`
    UpdatedAt time.Time `json: "updatedAt" bson: "updatedAt"`
    collection *mongo.Collection
}

Then query data using

func (u *User) FindByUsername(userName string) error {
    var ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)
    filter := bson.M{"username": userName}
    err := u.collection.FindOne(ctx, filter).Decode(&u)
    return err
}

The result that I'm getting is

{"Username":"jbond","FirstName":"","LastName":"","Email":"[email protected]","Gender":"Male","Password":"","Enabled":true,"BirthDate":"0001-01-01T00:00:00Z","CreatedAt":"0001-01-01T00:00:00Z","UpdatedAt":"0001-01-01T00:00:00Z"}

Most data are populated except for camel-case fields, and when I query from the console the data are there

> db.users.find().pretty()
{
    "_id" : ObjectId("xxxxxxxxxxxxxxxxxxxxxxxx"),
    "username" : "jbond",
    "firstName" : "James",
    "lastName" : "Bond",
    "email" : "[email protected]",
    "password" : "",
    "enabled" : true,
    "gender" : "Male",
    "birthDate" : {
        "type" : {
            "code" : "function Date() {\n    [native code]\n}"
        }
    },
    "createdAt" : {
        "type" : {
            "code" : "function Date() {\n    [native code]\n}"
        },
        "default" : {
            "code" : "function now() {\n    [native code]\n}"
        }
    },
    "updatedAt" : {
        "type" : {
            "code" : "function Date() {\n    [native code]\n}"
        },
        "default" : {
            "code" : "function now() {\n    [native code]\n}"
        }
    }
}

I don't understand why should it all be lowercase. Or am I missing something?


Solution

  • No, it is not failing decode camel-case fields. It is failing to parse struct tags.

    As per doc:

    By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.

    You should remove the space after json: and bson:.