Anonymous struct inheritance gives nested MongoDB document

46 views
Skip to first unread message

Sebastian Dahlgren

unread,
Sep 26, 2015, 3:05:33 AM9/26/15
to mgo-users
Hi all,

I have a struct like this

type UserUpdate struct {
Email     string  `thrift:"email,1,required" json:"email"`
Password  string  `thrift:"password,2,required" json:"password"`
Active    bool    `thrift:"active,3,required" json:"active"`
Firstname *string `thrift:"firstname,4" json:"firstname"`
Lastname  *string `thrift:"lastname,5" json:"lastname"`
}

And I wanna extend that with a ObjectId. So I have this:

type User struct {
Id bson.ObjectId `bson:"_id,omitempty"`
*user.UserUpdate
}

Finally I'm inserting this User struct into Mongo:

err = C.Insert(&User{
bson.NewObjectId(),
request.User,
})

This gives me an object in MongoDB that I didn't expect:

> db.users.find()
{ "_id" : ObjectId("5606408cdde2796e50000001"), "userupdate" : { "email" : "te...@example.com", "password" : "abc123", "active" : true, "firstname" : "Anakin", "lastname" : "Skywalker" } }

I want to get rid of the nesting with the "userupdate" thing in the document. I guess the root of the problem is the anonymous inheritance of structs that I'm doing. Please note that the UserUpdate struct is autogenerated with Thrift so I can't really modify that one.

Does anyone have a suggestion on what to do? Any pointers are greatly appreciated!

All the best,
Sebastian Dahlgren

Klaus Post

unread,
Sep 26, 2015, 5:57:46 AM9/26/15
to mgo-users
Hi!

Add `bson:",inline"` to *user.UserUpdate in the User struct.

/Klaus

Sebastian Dahlgren

unread,
Sep 26, 2015, 1:57:40 PM9/26/15
to mgo-users
Thanks that worked well, except that "inline" couldn't operate on pointers, so I had to update User to the following:

type User struct {
Id              bson.ObjectId `bson:"_id,omitempty"`
user.UserUpdate `bson:",inline"`
}

Cheers,
Sebastian
Reply all
Reply to author
Forward
0 new messages