无法从MongoDB获取完整文档

问题描述:

I have a mongodb collection with items in this form

    {
    "_id" : "base_519",
    "Name" : "Name",
    "Position" : 1000,
    "Type" : "Base",
    "Visible" : true,
    "Preview" : "/preview/preview.jpg",
    "IsBase" : true,
    "Product" : "product-2",
    "Categories" : [ 
        "category_1"
    ],
    "ObjData" : [ 
        {
            "_t" : "ObjDataNormal",
            "CanBuy" : false,
            "Foreground" : "/fg/foreground.gif",
            "Background" : "null.no.gif",
            "HasRatio" : false,
            "Ratio" : "0",
            "HasPadding" : true,
            "Padding" : 40,
            "Mask" : {
                "_id" : 0,
                "Name" : "",
                "X" : 39,
                "Y" : 85,
                "Width" : 422,
                "Height" : 332
            }
        }
    ]
}

but when i try to get the entire collection with go the ObjData field is not returned, instead i got this

{
        "id": "base_519",
        "name": "Name",
        "position": 1000,
        "type": "Base",
        "visible": true,
        "preview": "/preview/preview.jpg",
        "isbase": true,
        "product": "product-2",
        "categories": [
            "category_1"
        ]
    }

I am new to Go lang and this is just one of my first attempts at using the mongodb driver. The structs i use in Go are these

// Variant Struct
type Variant struct {
    ID         string        `json:"id,omitempty" bson:"_id,omitempty"`
    Name       string        `json:"name,omitempty" bson:"Name,omitempty"`
    Position   int           `json:"position,omitempty" bson:"Position,omitempty"`
    Type       string        `json:"type,omitempty" bson:"Type,omitempty"`
    Visible    bool          `json:"visible,omitempty" bson:"Visible,omitempty"`
    Preview    string        `json:"preview,omitempty" bson:"Preview,omitempty"`
    IsBase     bool          `json:"isbase,omitempty" bson:"IsBase,omitempty"`
    Product    string        `json:"product,omitempty" bson:"Product,omitempty"`
    Categories []string      `json:"categories,omitempty" bson:"Categories,omitempty"`
    ObjData    []ObjDataType `json:"objdata,omitempty" bson:"ObjData,omitempty"`
}

// ObjData Struct
type ObjDataType struct {
    Type       string   `json:"type,omitempty" bson:"_t,omitempty"`
    CanBuy     bool     `json:"canbuy,omitempty" bson:"CanBuy,omitempty"`
    Foreground string   `json:"foreground,omitempty" bson:"Foreground,omitempty"`
    Background string   `json:"background,omitempty" bson:"Background,omitempty"`
    HasRatio   bool     `json:"hasratio,omitempty" bson:"HasRatio,omitempty"`
    Ratio      float64  `json:"ratio,omitempty" bson:"Ratio,omitempty"`
    HasPadding bool     `json:"haspadding,omitempty" bson:"HasPadding,omitempty"`
    Padding    int      `json:"padding,omitempty" bson:"Padding,omitempty"`
    Mask       MaskType `json:"mask,omitempty" bson:"Mask,omitempty"`
}

// Mask Struct
type MaskType struct {
    ID     int    `json:"id,omitempty" bson:"_id,omitempty"`
    Name   string `json:"name,omitempty" bson:"Name,omitempty"`
    X      int    `json:"x,omitempty" bson:"X,omitempty"`
    Y      int    `json:"y,omitempty" bson:"Y,omitempty"`
    Width  int    `json:"width,omitempty" bson:"Width,omitempty"`
    Height int    `json:"height,omitempty" bson:"Height,omitempty"`
}

and i try to retrieve them using this function

func GetVariants(response http.ResponseWriter, request *http.Request) {
    response.Header().Add("content-type", "application/json")
    var variants []Variant
    collection := client.Database("FR-ToolService").Collection("Variants")
    ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
    cursor, err := collection.Find(ctx, bson.M{})
    if err != nil {
        response.WriteHeader(http.StatusInternalServerError)
        response.Write([]byte(`{ "message": "` + err.Error() + `"}`))
        return
    }
    defer cursor.Close(ctx)
    for cursor.Next(ctx) {
        var variant Variant
        cursor.Decode(&variant)
        variants = append(variants, variant)
    }
    if err := cursor.Err(); err != nil {
        response.WriteHeader(http.StatusInternalServerError)
        response.Write([]byte(`{ "message": "` + err.Error() + `"}`))
        return
    }
    json.NewEncoder(response).Encode(variants)
}

so what am i missing here? As i said i'm new to Go lang so i might not have understand well how the language and the mongo driver works

when i try to get the entire collection with go the ObjData field is not returned

The nested field ObjData is returned, but not decoded to the provided struct.

This is because the struct ObjDataType has one value that does not conform to the returned document. The struct has defined Ratio to be float64 but the document has a value of 0 in string.

You can fix this by either changing the struct definition, or the document value. i.e. change the struct to:

type ObjDataType struct {
    Type       string   `json:"type,omitempty" bson:"_t,omitempty"`
    CanBuy     bool     `json:"canbuy,omitempty" bson:"CanBuy,omitempty"`
    Foreground string   `json:"foreground,omitempty" bson:"Foreground,omitempty"`
    Background string   `json:"background,omitempty" bson:"Background,omitempty"`
    HasRatio   bool     `json:"hasratio,omitempty" bson:"HasRatio,omitempty"`
    Ratio      string  `json:"ratio,omitempty" bson:"Ratio,omitempty"`
    HasPadding bool     `json:"haspadding,omitempty" bson:"HasPadding,omitempty"`
    Padding    int      `json:"padding,omitempty" bson:"Padding,omitempty"`
    Mask       MaskType `json:"mask,omitempty" bson:"Mask,omitempty"`
}

A bonus tip for your learning journey, you can debug the decoding part of the code by using bson.M instead of your struct. For example:

for cursor.Next(ctx) {
    var variant bson.M
    cursor.Decode(&variant)
    variants = append(variants, variant)
    fmt.Println(variant)
}