首页 > 解决方案 > 从 Mongo 集合游标附加嵌套结构

问题描述

我遇到了将嵌套结构附加到数组的问题。

两者都有不同的嵌套值,但是当附加最后一个结构时,它会覆盖第一个嵌套结构。

这是该概念的一个简单示例。(我试图复制附加的嵌套结构,但它工作正常)https://play.golang.org/p/PseTHzV33uL

这是我实际代码中的结构

type Initiative struct {
    OID          primitive.ObjectID `bson:"_id,omitempty"json:"id,omitempty"`
    Cid          string             `json:"cid"`
    Name         string             `json:"name"`
    Description  string             `json:"description"`
    ProductName  string             `json:"product_name"`
    ProductId    string             `json:"product_id"`
    Quarter      string             `json:"quarter"`
    Year         string             `json:"year"`
    CustomFields []NestedField            `json:"custom_fields"`
}

type NestedField struct {
    Id    string `json:"id"`
    Cid   string `json:"cid"`
    Name  string `json:"name"`
    Type  string `json:"type"`
    Form  string `json:"form"`
    Value string `json:"value"`
}

type InitiativeResponse struct {
    ErrorCode        string       `json:"error_code,omitempty"`
    ErrorDescription string       `json:"error_description,omitempty"`
    Message          string       `json:"message,omitempty"`
    Payload          []Initiative `json:"payload,omitempty"`
}

这是我的职责。

func GetInitiativesFromDB(d *database.MongoDB, cid string) (response InitiativeResponse, err error) {
    filter := bson.M{"cid": cid}
    cur, err := d.Database.Collection(INITIATIVECOLLECTION).Find(context.Background(), filter, options.Find())
    fmt.Printf("%#v", cur)
    if err != nil {
        return response, errors.ErrorResponse{"No initiatives were found", 404}
    }
    var initiative Initiative
    for cur.Next(context.Background()) {
        err := cur.Decode(&initiative)
        if err != nil {
            return response, errors.ErrorResponse{"No initiatives were found", 404}
        }
        response.Payload = append(response.Payload, initiative)
        fmt.Printf("%#v", response.Payload)
    }
    if err := cur.Err(); err != nil {
        return response, errors.ErrorResponse{"No initiatives were found", 404}
    }
    _ = cur.Close(context.Background())
    return response, nil
}

这是我在第一次和第二次附加后打印数组的值时发现的。

请注意,第一次NestedFields 与第二次附加后的值不同。

第一个附加

[]api.Initiative{
    api.Initiative{
        OID:primitive.ObjectID{0x5d, 0xd9, 0x3f, 0x96, 0xd2, 0xc6, 0xb2, 0x95, 0x19, 0xd2, 0xbf, 0x98}, 
        Cid:"5d8502a2a284b46f3621f389", 
        Name:"1", 
        Description:"", 
        ProductName:"", 
        ProductId:"", 
        Quarter:"", 
        Year:"", 
        CustomFields:[]api.NestedField{
            api.NestedField{
                Id:"5db8ec9fee8040e9b6dfad87", 
                Cid:"5d8502a2a284b46f3621f389", 
                Name:"Test", 
                Type:"text", 
                Form:"initiative", 
                Value:"ggg"}, 
            api.NestedField{
                Id:"5dba0bcedf9cbf185683ecca", 
                Cid:"5d8502a2a284b46f3621f389", 
                Name:"Kylie", 
                Type:"text", 
                Form:"initiative", 
                Value:"ggg"}, 
            api.NestedField{
                Id:"5dd71d2af20bea1fef4564eb", 
                Cid:"5d8502a2a284b46f3621f389", 
                Name:"asdfasdf", 
                Type:"text", 
                Form:"initiative", 
                Value:"ggg"}}}}

第二个追加


[]api.Initiative{
    api.Initiative{
        OID:primitive.ObjectID{0x5d, 0xd9, 0x3f, 0x96, 0xd2, 0xc6, 0xb2, 0x95, 0x19, 0xd2, 0xbf, 0x98}, 
        Cid:"5d8502a2a284b46f3621f389", 
        Name:"1", 
        Description:"", 
        ProductName:"", 
        ProductId:"", 
        Quarter:"", 
        Year:"", 
        CustomFields:[]api.NestedField{
            api.NestedField{
                Id:"5db8ec9fee8040e9b6dfad87", 
                Cid:"5d8502a2a284b46f3621f389", 
                Name:"Test", 
                Type:"text", 
                Form:"initiative", 
                Value:"aaa"}, 
            api.NestedField{
                Id:"5dba0bcedf9cbf185683ecca", 
                Cid:"5d8502a2a284b46f3621f389", 
                Name:"Kylie", 
                Type:"text", 
                Form:"initiative", 
                Value:"aaa"}, 
            api.NestedField{
                Id:"5dd71d2af20bea1fef4564eb", 
                Cid:"5d8502a2a284b46f3621f389", 
                Name:"asdfasdf", 
                Type:"text", 
                Form:"initiative", 
                Value:""}}}, 
    api.Initiative{
        OID:primitive.ObjectID{0x5d, 0xd9, 0x3f, 0x9f, 0xd2, 0xc6, 0xb2, 0x95, 0x19, 0xd2, 0xbf, 0x99}, 
        Cid:"5d8502a2a284b46f3621f389", 
        Name:"2", 
        Description:"", 
        ProductName:"", 
        ProductId:"", 
        Quarter:"", 
        Year:"", 
        CustomFields:[]api.NestedField{
            api.NestedField{
                Id:"5db8ec9fee8040e9b6dfad87", 
                Cid:"5d8502a2a284b46f3621f389", 
                Name:"Test", 
                Type:"text", 
                Form:"initiative", 
                Value:"aaa"}, 
            api.NestedField{
                Id:"5dba0bcedf9cbf185683ecca", 
                Cid:"5d8502a2a284b46f3621f389", 
                Name:"Kylie", 
                Type:"text", 
                Form:"initiative", 
                Value:"aaa"}, 
            api.NestedField{
                Id:"5dd71d2af20bea1fef4564eb", 
                Cid:"5d8502a2a284b46f3621f389", 
                Name:"asdfasdf", 
                Type:"text",
                Form:"initiative", 
                Value:""}}}}

以及打印cur的结果

&mongo.Cursor{
    Current:bson.Raw(nil), 
    bc:(*driver.BatchCursor)(0xc000204000), 
    batch:(*bsoncore.DocumentSequence)(nil), 
    registry:(*bsoncodec.Registry)(0xc0000ee070), 
    clientSession:(*session.Client)(0xc0001f40c0), err:error(nil)}

有谁知道为什么会发生这种情况或如何解决?

标签: mongodbgo

解决方案


我发现当我var initiative Initiative进入循环时,它工作得很好。

func GetInitiativesFromDB(d *database.MongoDB, cid string) (response InitiativeResponse, err error) {
    filter := bson.M{"cid": cid}
    cur, err := d.Database.Collection(INITIATIVECOLLECTION).Find(context.Background(), filter, options.Find())
    fmt.Printf("%#v", cur)
    if err != nil {
        return response, errors.ErrorResponse{"No initiatives were found", 404}
    }
    for cur.Next(context.Background()) {
        var initiative Initiative
        err := cur.Decode(&initiative)
        if err != nil {
            return response, errors.ErrorResponse{"No initiatives were found", 404}
        }
        response.Payload = append(response.Payload, initiative)
        fmt.Printf("%#v", response.Payload)
    }
    if err := cur.Err(); err != nil {
        return response, errors.ErrorResponse{"No initiatives were found", 404}
    }
    _ = cur.Close(context.Background())
    return response, nil
}

推荐阅读