Golang mgo Finding

血红的双手。 提交于 2019-12-25 00:05:39

问题


I try to find my user in MongoDB but when I run this code :

type Person struct {
    Id bson.ObjectId `bson:"_id,omitempty"`//`json:"id" bson:"_id,omitempty"`
    username string `json:"username" bson:"username"`
    score string `json:"score" bson:"score"`
    level string `json:"level" bson:"level"`
}

result := Person{}
var id = "5b8a45912ed6f24d945bee38"
err = c.Find(bson.M{"_id":bson.ObjectIdHex(id)}).Select(bson.M{"username": 1, "score":1, "level": 1}).One(&result)

fmt.Println(result)

Just It show me :

{ObjectIdHex("5b8a45912ed6f24d945bee38") }

And don't return other value!

Thank you so much for your time!


回答1:


Just you should use the capital letter in first of struct names! And also you don't need

 Select(bson.M{"username": 1, "score":1, "level": 1})

You can write :

err = c.FindId(bson.ObjectIdHex(id)).One(&result)

Good Luck :))




回答2:


You have to export all struct fields subject to marshaling / unmarshaling, so change their name to start with capital letter:

type Person struct {
    Id       bson.ObjectId `bson:"_id,omitempty"`//`json:"id" bson:"_id,omitempty"`
    Username string        `json:"username" bson:"username"`
    Score    string        `json:"score" bson:"score"`
    Level    string        `json:"level" bson:"level"`
}

Also note that to find a document by its ID, you may use Collection.FindId():

err = c.FindId(bson.ObjectIdHex(id)).
    Select(bson.M{"username": 1, "score":1, "level": 1}).One(&result)


来源:https://stackoverflow.com/questions/52146057/golang-mgo-finding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!