繁体   English   中英

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

[英]Append new sub document to an array in the main struct

我的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"`
}

当我在端点localhost:3000/stations/<IDofTheStation/sensors处发出POST请求时,它应该向指定的工作站添加一个新的传感器。

目前我有此代码

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,因此会引发错误“ ObjectID必须正好为12个字节长(得到0)

将新的Sensor实例附加到Sensors数组(数据库将为其生成ID的传感器)的最佳方法是什么?

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

您真的需要传感器上的ID吗? MongoDB不会抱怨子文档没有ID (或者其ID格式错误),因为子文档可以具有任意结构-因此无需ID即可轻松存在。

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

sensor.ID := bson.NewObjectId()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM