Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongo: projection not affecting booleans

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"`
    ...
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading