While working on Golang Mongo Driver, I am stuck with this weird beahviour to use inline
Seems like bson:",inline"
doesnt work with Embedded Structs
.
Not able to understand why such a behaviour?
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))
}
But the same code works if I change
type Product struct {
ID primitive.ObjectID `bson:"_id"`
ProductId string `bson:"product_id" json:"product_id"`
Others bson.M `bson:",inline"`
}