Search code examples
mongodbgomgo

Relationships in mgo


I've written some simple program with golang and mgo. My question is how to properly to 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 a slice of Users. I can $push a pointer to a User and it just works fine. The thing is that I only want to store a reference to the user and not nesting it:

2nd 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 output I want - but now it's not visible from the struct which nested structs are referenced. Does mgo provide some mechanism to deal with this?


Solution

  • mgo is a db driver library and not an ORM.. What I'd do is have the ids array as in the 2nd example (unexported, with lowercase) and have a Friends() method which queries the db by those ids and return a []User