[英]MongoDB fetching all the documents in a collection gives an empty slice of structs using mgo
I have inserted data into mongodb in the following way 我已通过以下方式将数据插入到mongodb中
{
"_id" : ObjectId("5c80e9cc3bf127cfc80ba5dc"),
"resp" : [
{
"name" : "by",
"gender" : "synced",
"age" : "response",
"hobby" : "submitted",
"mobile" : "revision"
},
{
"name" : "byoooooo",
"gender" : "sytewed",
"age" : "se",
"hobby" : "subed",
"mobile" : "revissaaon"
}
]
}
Using this method 使用这种方法
func (d *CollectDAO) Insert(responses []*models.FormData) error {
resp := models.Responses{
Data: responses,
}
err := db.C(formsCollection).Insert(resp)
return err
}
This is the struct used in the insert method 这是insert方法中使用的结构
type FormData struct {
Name string `csv:"name" json:"name" bson:"name"`
Gender string `csv:"gender" json:"gender" bson:"gender"`
Age string `csv:"age" json:"age" bson:"age"`
Hobby string `csv:"hobby" json:"hobby" bson:"hobby"`
MobileNo string `csv:"mobile" json:"mobile" bson:"mobile"`
}
The handler reads sample csv data from a file. 处理程序从文件中读取示例csv数据。 This is the csv data 这是CSV数据
name,gender,age,hobby,mobile
by,synced,response,submitted,revision
byoooooo,sytewed,se,subed,revissaaon
And then inserts that into mongo 然后将其插入mongo
When querying all the documents of my collection I get an empty response 查询集合中的所有文档时,我得到一个空响应
func (d *CollectDAO) FindAll() (models.Responses, error) {
var responses []models.Responses
err := db.C(formsCollection).Find(nil).All(&responses)
if err != nil {
log.Fatal(err)
}
log.Printf("all docs %v\n", responses)
return responses, err
}
When I try to log the value of the struct I get an empty struct. 当我尝试记录该结构的值时,我得到一个空结构。 This is the responses struct that I am using at the end to put the slice of response in. 这是我最后用来放入响应片段的响应结构。
type Responses struct {
Data []*FormData `json:"response"`
}
What am I doing wrong? 我究竟做错了什么? I just need to implement a handler that will return all the data in a collection as a struct. 我只需要实现一个处理程序即可将集合中的所有数据作为结构返回。
On the client side I get this error 在客户端,我收到此错误
unexpected end of JSON input
{ObjectIdHex("") []}
The mgo
package uses the bson
tag to map struct fields to document fields in MongoDB. mgo
软件包使用bson
标记将结构字段映射到MongoDB中的文档字段。
So your Responses
type should look something like this: 因此,您的Responses
类型应如下所示:
type Responses struct {
Data []*FormData `json:"response" bson:"resp"`
}
Note that you have to save documents with this struct (with bson
tag) to be able to fetch results into values of this type. 请注意,您必须使用此结构(带有bson
标记)保存文档,才能将结果提取到这种类型的值中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.