简体   繁体   English

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

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

I have the following go structs in my MongoDB database: 我的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"`
}

When I make a POST request at the endpoint localhost:3000/stations/<IDofTheStation/sensors , it should add a new sensor to the specified station. 当我在端点localhost:3000/stations/<IDofTheStation/sensors处发出POST请求时,它应该向指定的工作站添加一个新的传感器。

Currently I have this code 目前我有此代码

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

The problem is that it does not automatically generate an ID for the new sensor that I want to add, thus it throws the error " ObjectIDs must be exactly 12 bytes long (got 0) " 问题在于,它不会自动为我要添加的新传感器生成ID,因此会引发错误“ ObjectID必须正好为12个字节长(得到0)

What is the best way to append a new Sensor instance to the Sensors array where the DB generates the id for the sensor? 将新的Sensor实例附加到Sensors数组(数据库将为其生成ID的传感器)的最佳方法是什么?

MongoDB won't ever generate an ID for a sub-document on the server-side. MongoDB永远不会在服务器端为子文档生成ID

Do you really need the ID on the sensor? 您真的需要传感器上的ID吗? MongoDB won't complain about a sub-document not having an ID (or its ID being in a wrong format) because a subdocument can have an arbitrary structure - so it can easily exist without an ID . MongoDB不会抱怨子文档没有ID (或者其ID格式错误),因为子文档可以具有任意结构-因此无需ID即可轻松存在。

If you do need the ID for some reason then you can, of course, create one on the client side: 如果由于某种原因确实需要ID,那么您当然可以在客户端创建一个ID:

sensor.ID := bson.NewObjectId()

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

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