Skip to content

Auto type assertion not working when fetching data #383

Open
@voidhofer

Description

@voidhofer

I switched from go-mgo/mgo.v2 to this as it was advised by many but I found an odd problem.
While in go-mgo's version it was possible to fetch results to a struct object with this package it is not possible.

Every time I use "c.Find(nil).One(&result)" to fetch data into a struct I get an empty struct.
I have to manually marshal and unmarshal the data to get it into a struct otherwise it will not work.

Example:

type Menu struct {
    ID       bson.ObjectId 'json:"_id" bson:"_id"'
    Value string                'json:"val" bson:"val"'
}

func GetData() (Menu, error) {
        var err error
        var result interface{}
        var resultMenu Menu
        if database.CheckConnection() {
		session := database.Mongo.Copy()
		defer session.Close()
		c := session.DB(database.ReadConfig().MongoDB.Database).C("menus")
		err = c.FindId(bson.ObjectIdHex("5b6d851c9d8c2119e3667a99")).One(&result) // using resultMenu instead of result will return an empty Menu object
	} else {
		err = ErrUnavailable
	}
	bsonBytes, _ := bson.Marshal(result)         // have to manually marshal and unmarshal data
	bson.Unmarshal(bsonBytes, &resultMenu)
	return resultMenu, standardizeError(err)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions