亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將新的子文檔附加到主結構中的數組

將新的子文檔附加到主結構中的數組

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 關注
  • 121 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號