Frage

My object I have in collection:

type Room struct {
    Id bson.ObjectId            `json:"Id"                  bson:"_id"`
    Name string                 `json:"Name"                bson:"name"`
}

Inserting into collection:

room = &Room{Id: bson.NewObjectId(), Name: "test"}
RoomCollection.Insert(room)

Retrieving from collection (any):

roomX := &Room{}
if err := RoomCollection.Find(bson.M{}).One(roomX); err != nil {
    panic(err)
}
fmt.Printf("RoomX %s:\n%+v\n\n", roomX.Id, roomX)

This outputs:

RoomX ObjectIdHex("52024f457a7ea6334d000001"):
&{Id:ObjectIdHex("52024f457a7ea6334d000001") Name:test}

Retrieving from collection (by id):

roomZ := &Room{}
if err := RoomCollection.Find(bson.M{"_id": room.Id}).One(roomZ); err != nil {
    panic(err) // throws "not found"
}

This throws "not found" and I can't figure out why.

War es hilfreich?

Lösung

The different key-value tags for a field should, according to the reflect package, be separated with space.

By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.

The mgopackage fails to read the tag and stores the Id value as id instead of _id.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top