【问题标题】:Empty Array being returned返回空数组
【发布时间】:2017-07-12 22:36:52
【问题描述】:

我创建了一个 ionic 应用程序,我目前正试图通过 Go 从 MongoDB 检索一个数组。这就是 MongoDB 中的数据的样子。

{
"_id": {
    "$oid": "58a86fc7ad0457629d64f569"
},
"name": "ewds",
"username": "affe@dsg.com",
"password": "vdseaff",
"email": "fawfef",
"usertype": "Coaches",
"Requests": [
    "test@t.com"
]
}

我目前正在尝试取回请求字段,其中一种方法是尝试使用以下代码接收整个文档。

//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)

这仅返回带有空数组的以下内容。

{ewds affe@dsg.com vdseaff fawfef Coaches []}

【问题讨论】:

  • 更新问题以显示results的定义。
  • 有错误吗?
  • 没有错误。它的意思是返回数组而不是空数组

标签: arrays mongodb go ionic-framework


【解决方案1】:

在您的数据中,Requests 字段的大写字母为 Rbson 库将 mongo 文档转换为您的 struct 类型有这样的说法

https://godoc.org/gopkg.in/mgo.v2/bson#Unmarshal

小写的字段名称用作每个导出字段的键,但可以使用相应的字段标签更改此行为。

因此,您可以选择在Requests 字段中添加标签,或者将数据更改为使用小写requests。如果您选择标签选项,它会像

Requests []string `bson:"Requests"`

【讨论】:

  • 非常感谢。
猜你喜欢
  • 1970-01-01
  • 2021-08-11
  • 2017-02-27
  • 2020-04-01
  • 2019-04-17
  • 2017-04-24
  • 2019-09-13
  • 2018-02-03
  • 2019-07-05
相关资源
最近更新 更多