英文:
Mongo: projection not affecting booleans
问题
我注意到的一件事是,我可以设置投影,不返回我的username
或userID
字符串,没有问题。然而,当尝试不返回deactivated
或admin
布尔值时,它们仍然出现,即使其他字符串不会出现。
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"`
...
}
英文:
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"`
...
}
答案1
得分: 1
你看到的值是结构字段的默认值。我建议你使用指向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"`
...
}
在这个例子中,这些值将是nil
。
英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论