mongodb - 结构中的省略不省略

标签 mongodb go

我试图在不发送空数据的情况下将数据存储到 MongoDB。有问题的结构是投票和问题。传入数据的范围从有 2 个问题到 5 个问题。因此,如果用户只输入 2 个问题,我将不需要使用 Poll 结构中的其他 3 个字段。我宁愿让这些字段根本不出现,也不愿将空数据发送到服务器。

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)
  }
}

最佳答案

添加 mgo BSON 编码器使用的 bson 键。编码器忽略 json 键。参见 bson.Marshal有关详细信息的文档。

type Poll struct {
    Id     bson.ObjectId `bson:"_id"`
    Quest0 *Question     `json:"quest0,omitempty" bson:"ques0:omitempty"`
    ...

关于mongodb - 结构中的省略不省略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53790068/

相关文章:

java - 获取最后插入的带有标签 MongoDB Java 的文档

eclipse - eclipse 上的 Golang : "Resource doesn' t have a corresponding Go package"on Mac

go - Println 改变 slice 的容量

python - 在 Go 中获取 `/etc/environment`

javascript - 动态更改 MongoDB 查找结果

javascript - Mongoose 不会在生产 (Heroku) 上填充 (.populate()),但可以在本地工作

javascript - mongoose.findOneAndUpdate 返回 null

amazon-web-services - 使用 AWS Go 开发工具包的动态 list

json - 如何获取从ajax发送的JSON数据并解析为变量

Mongodb:$expr比较同一文档中同一数组的两个元素