duanjinchi1982 2018-12-15 06:19
浏览 37
已采纳

结构中的遗漏不遗漏

I'm trying to store data to MongoDB without sending null data. The Struct in question is Poll and Question. Incoming data can range from have 2 questions, to 5. So if a user only enters 2 questions I wont have a need to use the 3 other fields in Poll struct. Id rather have the fields not appear at all than send null data to the server.

package main

// Omit Empty not working
type Poll struct {
Id     bson.ObjectId `bson:"_id"`
  Quest0 *Question     `json:"quest0,omitempty"`
  Quest1 *Question     `json:"quest1,omitempty"`
  Quest2 *Question     `json:"quest2,omitempty"`
  Quest3 *Question     `json:"quest3,omitempty"`
  Quest4 *Question     `json:"quest4,omitempty"`
  Quest5 *Question     `json:"quest5,omitempty"`
}

type Question struct {
  Count    *int    `json:"count,omitempty"`
  Question *string `json:"question,omitempty"`
}

type ReceivedPoll struct {
  Quest0 string `db:"quest0"`
  Quest1 string `db:"quest1"`
  Quest2 string `db:"quest2"`
  Quest3 string `db:"quest3"`
  Quest4 string `db:"quest4"`
  Quest5 string `db:"quest5"`
}

func main() {
  fmt.Println("server running...")

  router := httprouter.New()

  router.POST("/api/create", api)
  router.NotFound = http.FileServer(http.Dir("./public"))
  log.Fatal(http.ListenAndServe(":5000", router))
}

func api(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {

  w.Header().Set("Content-type", "application/json")

  session, err := mgo.Dial(mkey)

  if err != nil {
    panic(err)
  }

  defer session.Close()
  fmt.Println("is this running?")

  switch r.URL.String() {
    case "/api/create":
      // LOOK HERE
      poll := &Poll{}

      json.NewDecoder(r.Body).Decode(&poll)

      poll.Id = bson.NewObjectId()
      fmt.Println(*poll)

      c := session.DB("abase").C("polls")
      err = c.Insert(*poll)
      if err != nil {
        fmt.Println(err)
      }

      rz, _ := json.Marshal(poll.Id)
      w.Write(rz)
  }
}
  • 写回答

1条回答 默认 最新

  • douju7765 2018-12-15 06:29
    关注

    Add the bson key used by the mgo BSON encoder. The encoder ignores the json key. See bson.Marshal documentation for the details.

    type Poll struct {
        Id     bson.ObjectId `bson:"_id"`
        Quest0 *Question     `json:"quest0,omitempty" bson:"ques0:omitempty"`
        ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染