Mongo: projection not affecting booleans

Issue

Something I’ve noticed is that I can set the projection to not return my username or userID strings with out a problem. However, when trying to not return the deactivated or admin boolean, they still appear even when the other strings wont?

    user := model.User{}
    filter := bson.D{
        {
            Key:   "_id",
            Value: userID,
        },
    }
    projection := bson.D{
        {
            Key:   "password",
            Value: 0,
        },
        {
            Key:   "username",
            Value: 0,
        },
        {
            Key:   "_id",
            Value: 0,
        },
        {
            Key:   "deactivated",
            Value: 0,
        },
        {
            Key:   "admin",
            Value: 0,
        },
    }
    options := options.FindOne().SetProjection(projection)
    _ = usersCol.FindOne(ctx, filter, options).Decode(&user)

&{ false false [0xc00028d180] 0xc0002b0900 0xc0002bdce0 <nil>}

type User struct {
    ID           string          `json:"id" bson:"_id"`
    Admin        bool            `json:"admin"`
    Deactivated  bool            `json:"deactivated"`
    Username     string          `json:"username"`
    Password     string          `json:"password"`
    ...
}

Solution

The values you see it is default value of struct field. I suggest you to use pointer to the field of User:

type User struct {
    ID           string           `json:"id" bson:"_id"`
    Admin        *bool            `json:"admin"`
    Deactivated  *bool            `json:"deactivated"`
    Username     string           `json:"username"`
    Password     string           `json:"password"`
    ...
}

In this example values would be nil.

Answered By – Philidor

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.