简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM