Relationships in mgo

I wrote a simple program with golang and mgo. My question is how to properly treat relationships in mgo.

1st approach:

type User struct {
    Id       bson.ObjectId   `json:"_id,omitempty" bson:"_id,omitempty"`
    Username string          `json:"username" bson:"username"`
    Email    string          `json:"email" bson:"email"`
    Password string          `json:"password" bson:"password"`
    Friends  []User          `json:"friends" bson:"friends"`
}

      

" Friends " - is part of the user. I can $ push the pointer to the user and it just works fine. The thing is, I want to keep the link to the user only and not embed it:

Second approach:

type User struct {
    Id       bson.ObjectId   `json:"_id,omitempty" bson:"_id,omitempty"`
    Username string          `json:"username" bson:"username"`
    Email    string          `json:"email" bson:"email"`
    Password string          `json:"password" bson:"password"`
    Friends  []bson.ObjectId `json:"friends" bson:"friends"`
}

      

This gives me the result that I want, but now it doesn't show up in the structure that the nested structures referenced. Does mgo provide any mechanism to combat this?

+3


source to share


1 answer


mgo is a db driver library, not an ORM. What I would do is have an array of IDs like in the second example (no extension, lowercase) and have a Friends () method that asks the db for these IDs and returns [] User



+7


source







All Articles