Hey guys,
So I have structs that look like this:
type Product struct {
ProductName string `bson:"productName,omitempty" json:"productName"`
ProductID string `json:"productID" bson:"productID,omitempty"`
Variants []Variant `json:"variants" bson:"variants,omitempty"`
}
type Variant struct {
VariantID string `json:"variantID" bson:"variantID,omitempty"`
VariantName string `json:"variantName" bson:"variantName,omitempty"`
Size string `json:"size" bson:"size,omitempty"`
Image string `json:"image" bson:"image,omitempty"`
Quantity int `json:"quantity" bson:"quantity,omitempty"`
Price float64 `json:"price" bson:"price,omitempty"`
}
And I’m trying to decode bson from my database into the structs. Here is the code:
coll := client.Database(DbName).Collection(ProductCollectionName)
cursor, _ := coll.Find(ctx, bson.M{})
for cursor.Next(ctx) {
var p Product
err := cursor.Decode(&p)
if err != nil {
fmt.Println(err) // prints "error decoding key variants: cannot decode document into Variant"
}
fmt.Println(p) // prints ProductName and ProductID fine, prints an empty array for Variants
}
I was wondering what I would have to do to adjust my code so the document gets decoded into Variants properly as well?