dongyu9894 2019-07-19 15:07
浏览 78
已采纳

无法从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

  • 写回答

1条回答 默认 最新

  • douwen8118 2019-07-24 04:32
    关注

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

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退