首页 > 解决方案 > 在 Go 中初始化 MongoDB 数组字段

问题描述

我有这个数据模式:

"person": {
  "name": "John",
  "pets": [
    {
      "name": "Birdie"
    }
  ]
}

这是将 Person 文档插入 MongoDB 的结构:

type Person struct {
  Id   primitive.ObjectID `bson:"_id,omitempty" json:"id"`
  Name string `json:"name"`
  Pets []struct {
    Name string `json:"name"`
  } `json:"pets"
}

当 JSON 发送到不带 pets 字段的 POST Person API 时,记录的 MongoDB 文档将 pets 字段设置为 null。我认为这是因为 go 中的 slices 的 nil 值为零而不是空数组?

personPostRequest := ds.Person{}
if err := c.ShouldBindJSON(&personPostRequest); err != nil {
    c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
    return
}

将宠物初始化为 null 很麻烦,因为在将宠物添加到文档时无法使用 addToSet:

// Will render the error  Cannot apply $addToSet to non-array field.
// Field named 'pets' has non-array type null
err = collection.FindOneAndUpdate(
    ctx,
    bson.M{"_id": personId},
    bson.M{
        "$addToSet": bson.M{
            "pets": bson.M{"$each": pets},
        },
    },
    &opt,
)

我可以通过将 struct 标签添加bson:,omitempty到 pets 来解决这个问题,但我喜欢探索可以在 MongoDB 中将 pets 初始化为空数组的解决方案。我如何在 Go 中做到这一点?我正在使用 Go gin 框架。谢谢

标签: arraysmongodbgostructgo-gin

解决方案


推荐阅读