Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto type assertion not working when fetching data #383

Open
voidhofer opened this issue Nov 26, 2019 · 0 comments
Open

Auto type assertion not working when fetching data #383

voidhofer opened this issue Nov 26, 2019 · 0 comments

Comments

@voidhofer
Copy link

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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant