Пн go Go Драйвер - встроенный со встроенными структурами не работает - PullRequest
0 голосов
/ 10 апреля 2020

При работе на Golang Пн go Драйвер, я застрял с этим странным beahviour использовать inline

Похоже, bson:",inline" не работает с Embedded Structs.

Не в состоянии понять, почему такое поведение?

inline Inline the field, which must be a struct or a map, causing all of its fields or keys to be processed as if they were part of the outer struct. For maps, keys must not conflict with the bson keys of other struct fields.

import (
    "context"
    "encoding/json"
    "fmt"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/bson/primitive"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

//Expected Output
//{
//  "ID": "5e6e96cb3cfd3c0447d3e368",
//  "product_id": "5996",
//  "Others": {
//      "some": "value"
//  }
//}

//Actual Output
//{
//  "ID": "5e6e96cb3cfd3c0447d3e368",
//  "product_id": "5996"
//}

type Product struct {
    ID        primitive.ObjectID `bson:"_id"`
    ProductId string             `bson:"product_id" json:"product_id"`
    *SchemalessDocument
}

type SchemalessDocument struct {
    Others    bson.M             `bson:",inline"`
}


func main() {

    clientOptions := options.ClientOptions{
        Hosts: []string{"localhost"},
    }
    client, _ = mongo.NewClient(&clientOptions)
    client.Connect(context.TODO())
    var p Product
    collection := client.Database("Database").Collection("collection")
    query := bson.D{{"product_id", "5996"}}
    _ = collection.FindOne(context.TODO(), query).Decode(&p)

    jsonResp, _ := json.Marshal(p)
    fmt.Println(string(jsonResp))

}

Но тот же код работает, если я изменяю

type Product struct {
    ID        primitive.ObjectID `bson:"_id"`
    ProductId string             `bson:"product_id" json:"product_id"`
    Others    bson.M             `bson:",inline"`
}
...