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 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!