简体   繁体   中英

Append new sub document to an array in the main struct

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM