doudiejian5827 2019-03-07 16:09
浏览 93

MongoDB提取集合中的所有文档,使用mgo给出了空的结构片段

I have inserted data into mongodb in the following way

  {
     "_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

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. This is the csv data

name,gender,age,hobby,mobile
by,synced,response,submitted,revision
byoooooo,sytewed,se,subed,revissaaon

And then inserts that into 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
", 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("") []}
  • 写回答

1条回答 默认 最新

  • dongliang1873 2019-03-07 16:14
    关注

    The mgo package uses the bson tag to map struct fields to document fields in MongoDB.

    So your Responses type should look something like this:

    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.

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!