0

The documents in collection look like this :

    {
     "id":"81f003b9-da3a-4480-9963-c9c8e01027af"
     "name": "name",
     "born": "birth date",
     "birthplace": "place"
    }

I want to get only id and name elements from the document. My go code is this,

 type Player struct {
    Id                   string       `json:"id"`
    PlayerName           string       `json:"name"`
    Born                 string       `json:"born, omitempty"`
    BirthPlace           string       `json:"birthplace, omitempty"`
}


func GetIDName(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")

var players []Player

opts := options.Find().SetProjection(bson.D{{"id", 1}, {"name", 1}})
cur, err := collection.Find(context.TODO(), bson.M{"status": 1}, opts)

if err != nil {
    fmt.Fprintf(w, string("Invalid request payload"))
    respondWithError(w, http.StatusBadRequest, "Invalid request payload")
    return
}
defer r.Body.Close()

defer cur.Close(context.TODO())

for cur.Next(context.TODO()) {

    var player Player

    err := cur.Decode(&player)
    if err != nil {
        log.Fatal(err)
    }

    players = append(players, player)
 }

 if err != nil {
    return
 } 
  respondWithJSON(w, http.StatusOK, players)
}

The expected output was

{
  {
     "id":"81f003b9-da3a-4480-9963-c9c8e01027af",
     "name": "name"
  },
  {
     "id":"81787162976217t895789127",
     "name": "the other name"
  }
}

However, the output I get is,

 {
  {
     "id":"81f003b9-da3a-4480-9963-c9c8e01027af",
     "name": "",
      "born": "",
      "birthplace": ""
  },
  {
     "id":"81787162976217t895789127",
     "name": "",
     "born": "",
     "birthplace": ""
  }
}

As you can see, from the query above, I can't get the name, and the other fields are output too with nil values. It'll be really helpful if you could tell me what I am doing wrong. Thanks!

RandomUser
  • 93
  • 1
  • 8

1 Answers1

0

Just to limit the problem, first verify that you're getting the correct info from the database. Then, that you're Decoding it right. Finally, that the JSON output is omitting empty fields.

It's a good practice to use log.Printf() for this purpose.

Cknu
  • 186
  • 1
  • 7