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()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探