簡體   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