从Mongo Collection游标追加嵌套结构

时间:2019-11-23 16:35:07

标签: mongodb go

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

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

这里是一个简单的概念示例。 (我尝试复制附加的嵌套结构,但效果很好)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
}

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

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

首次添加

[]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:""}}}}

打印结果

&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)}

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

1 个答案:

答案 0 :(得分:0)

我发现当我在循环中移动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
}