0

在使用 Golang Mongo Driver 时,我被这种奇怪的行为所困扰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"`
}
4

1 回答 1

0

这是应该的

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

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

于 2021-08-21T08:02:13.383 回答