Search code examples
gobsonmgo

Model relationships in mgo


I'm writing a db interface with mgo. Some documents in my model reference other documents.

type Child struct{
    Id       bson.ObjectId   `json:"_id,omitempty" bson:"_id,omitempty"`
    C        string
}

type Parent struct {
    Id       bson.ObjectId   `json:"_id,omitempty" bson:"_id,omitempty"`
    A        string          
    B        Child           
}

child := Child{
    Id: bson.NewObjectId(),
    C: "panino"
}

parent := Parent{
    Id: bson.NewObjectId(),
    A: "Just a string",
    B: child,
}

My aim is to:

  1. keep these documents embedded in the code,
  2. store parent in Parents collection with only a reference to child,
  3. store child in Children collection as a standalone document.

The following:

type Child struct{
    Id       bson.ObjectId   `json:"_id,omitempty" bson:"_id,omitempty"`
    C        string          `bson:"-"`
}

succeeds in 1 and 2 but only child.Id get stored in Children collection. I'm very new to Golang/mgo. I played a bit with Marshaling and Unmarshaling, but I don't quite understand how Getter and Setter work. I have the feeling they would do the trick though. Any clue?


Solution

  • You are probably looking for the bson:",omitempty" tag instead of bson:"-". The former will omit the field only if it is empty, instead of at all times. Alternatively, you can also have a secondary ChildReference type that is used on references only. It's fine to use different types with the same collection.

    As an aside, note that although that practice is used in some situations, you don't have to store the collection name next to the document id in all cases. The most common practice for well defined schemas is to store simply the document id (e.g. with {"person_id": 123} the meaning is clear).