登录
首页 >  Golang >  Go问答

Golang 调查结果

来源:stackoverflow

时间:2024-04-12 08:27:36 262浏览 收藏

大家好,今天本人给大家带来文章《Golang 调查结果》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我尝试在 mongodb 中找到我的用户,但是当我运行此代码时:

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)

只是它告诉我:

{objectidhex("5b8a45912ed6f24d945bee38") }

并且不要返回其他值!

非常感谢您抽出时间!


解决方案


只是你应该在结构名称的第一个中使用大写字母! 而且你也不需要

select(bson.m{"username": 1, "score":1, "level": 1})

你可以写:

err = c.findid(bson.objectidhex(id)).one(&result)

祝你好运:))

您必须导出所有需要编组/解组的结构字段,因此将它们的名称更改为以大写字母开头:

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

另请注意,要通过 id 查找文档,您可以使用 Collection.FindId()

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

理论要掌握,实操不能落!以上关于《Golang 调查结果》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>