arrays - 在 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 框架。谢谢
解决方案
推荐阅读
- android - 过滤列表时RecyclerView高度变化
- search - 基于键值识别的 MERN Stack 项搜索
- python - CVXPY 约束公式
- java - 启动画面徽标图像上的动画
- openai - 没有名为 retro.import 的模块 Open AI
- arrays - 修复char格式化错误——Linux系统C程序
- c - 找到能被 7 整除的最小值
- python - Visual Studio Code 找不到我的 python 文件。[Errno 2] 没有这样的文件或目录
- python - FastAPI 重定向给出了不允许的方法错误
- r - 使 CRAN R 包建议 GitHub R 包