I need to get a document from MongoDB and put it into a struct with custom type.
type translate_t struct {
Sources []string `bson:"sources"`
Targets []string `bson:"targets"`
}
type practice_t struct {
Id primitive.ObjectID `bson:"_id"`
Translate translate_t `bson:"translate"`
}
The data in the database is as expected.
"practice": {
"translate": {
"sources": ["data", "more data"]
"target": ["even", "more", "data"]
}
}
What I do (very basic):
var item practice_t
err = collection.FindOne(ctx, filter).Decode(&item)
log.Printf("item:%+v", item)
The log prints this:
{Id:ObjectId("5deeblablabla"), Translate:{Sources:[] Targets:[]}} //where is my sweet data?
Now, I want to point out that all the other items (not nested with custom struct) get decoded properly. So, it seems to me that the Decode() function doesn't like custom structs... This looks like a very common task, so am I missing anything? I've been reading about overriding the default Decoder or something like that, but that seems way too much work for something this simple.
You are missing "practice":
type doc struct {
Practice practice_t `bson:"practice"`
}
The database document has to structurally match the document you're unmarshaling. You showed the database document is an object with a practice
field. Then you must have a struct with a field tagged with practice
.