英文:
Empty Array being returned
问题
我已经创建了一个Ionic应用程序,目前我正试图通过Go从MongoDB中检索一个数组。这是MongoDB中的数据样式:
{
"_id": {
"$oid": "58a86fc7ad0457629d64f569"
},
"name": "ewds",
"username": "affe@dsg.com",
"password": "vdseaff",
"email": "fawfef",
"usertype": "Coaches",
"Requests": [
"test@t.com"
]
}
我目前正在尝试获取"Requests"字段,其中一种尝试的方法是使用以下代码接收整个文档:
//这是使用的结构体。
type (
User struct {
Name string
Username string
Password string
Email string
UserType string
Requests []string
}
)
results := User{}
err = u.Find(bson.M{"username": Cname}).One(&results)
这只返回以下内容,其中包含一个空数组:
{ewds affe@dsg.com vdseaff fawfef Coaches []}
英文:
I have created an ionic app and I am currently stuck trying to retrieve an array back from MongoDB through Go. This is what the data in MongoDB looks like.
{
"_id": {
"$oid": "58a86fc7ad0457629d64f569"
},
"name": "ewds",
"username": "affe@dsg.com",
"password": "vdseaff",
"email": "fawfef",
"usertype": "Coaches",
"Requests": [
"test@t.com"
]
}
I am currently trying to get back the Requests field one of the ways I tried was trying to receive the whole document using the following code.
//this is the struct being used.
type (
User struct {
Name string
Username string
Password string
Email string
UserType string
Requests []string
}
)
results := User{}
err = u.Find(bson.M{"username": Cname}).One(&results)
This only returns the following with an empty array.
{ewds affe@dsg.com vdseaff fawfef Coaches []}
答案1
得分: 1
在你的数据中,Requests
字段的首字母是大写的R
。将Mongo文档转换为你的结构类型的bson
库有以下说明:
https://godoc.org/gopkg.in/mgo.v2/bson#Unmarshal
> 小写的字段名用作每个导出字段的键,但是可以使用相应的字段标签更改此行为。
因此,你有两个选择:要么给Requests
字段添加一个标签,要么将你的数据改为使用小写的requests
。如果选择标签选项,可以这样写:
Requests []string `bson:"Requests"`
英文:
In your data the Requests
field has a capital R
. The bson
library that converts the mongo document to your struct type has this to say
https://godoc.org/gopkg.in/mgo.v2/bson#Unmarshal
> The lowercased field name is used as the key for each exported field, but this behavior may be changed using the respective field tag.
So your options are to either add a tag to your Requests
field or change your data to use lowercase requests
. If you choose the tag option it would be like
Requests []string `bson:"Requests"`
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论