dornc9470 2018-10-22 16:32
浏览 109
已采纳

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

I have the following go structs in my MongoDB database:

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.

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

What is the best way to append a new Sensor instance to the Sensors array where the DB generates the id for the sensor?

  • 写回答

1条回答 默认 最新

  • doubailian4459 2018-10-22 18:33
    关注

    MongoDB won't ever generate an ID for a sub-document on the server-side.

    Do you really need the ID on the sensor? 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.

    If you do need the ID for some reason then you can, of course, create one on the client side:

    sensor.ID := bson.NewObjectId()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败