我的 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()
- 1 回答
- 0 關注
- 121 瀏覽
添加回答
舉報
0/150
提交
取消