为了账号安全,请及时绑定邮箱和手机立即绑定

将新的子文档附加到主结构中的数组

将新的子文档附加到主结构中的数组

Go
阿波罗的战车 2023-04-24 16:53:27
我的 MongoDB 数据库中有以下 go 结构:type Station struct {    ID          bson.ObjectId `bson:"_id" json:"id"`    Name        string        `bson:"name" json:"name"`    Sensors     []Sensor `bson:"sensors" json:"sensors"`}type Sensor struct {    ID             bson.ObjectId `bson:"_id" json:"id"`    Type string `  bson:"type" json:"type"`    Value float64 `bson:"value" json:"value"`}当我在端点发出 POST 请求时localhost:3000/stations/<IDofTheStation/sensors,它应该向指定站添加一个新传感器。目前我有这段代码func AddSensorToStation(w http.ResponseWriter, r *http.Request) {    defer r.Body.Close()    params := mux.Vars(r)    station, err := dao.FindById(params["id"])    if err != nil {        respondWithError(w, http.StatusBadRequest, "Invalid Station ID")        return    }    sensor := Sensor{Type: "test"}    station.Sensors = append(station.Sensors, sensor)       if err := dao.Update(station); err != nil {        respondWithError(w, http.StatusInternalServerError, err.Error())        return    }    respondWithJson(w, http.StatusOK, station)}问题是它不会为我要添加的新传感器自动生成 ID,因此会抛出错误“ ObjectIDs 必须恰好 12 个字节长(得到 0) ”将新的 Sensor 实例附加到数据库为传感器生成 id 的 Sensors 数组的最佳方法是什么?
查看完整描述

1 回答

?
不负相思意

TA贡献1777条经验 获得超10个赞

MongoDB 永远不会ID在服务器端为子文档生成一个。

你真的需要ID传感器吗?MongoDB 不会抱怨子ID文档ID没有ID.

如果您出于某种原因确实需要 ID,那么您当然可以在客户端创建一个:

sensor.ID := bson.NewObjectId()


查看完整回答
反对 回复 2023-04-24
  • 1 回答
  • 0 关注
  • 65 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信