borislemke
borislemke

Reputation: 9116

Nested documents in model struct

Say I have a UserModel like so:

type (
    OrderModel struct {
         ID   bson.ObjectId `json:"id" bson:"_id"`
         ...
    }

    UserModel struct {
         ...
         // What do I store here? Is this an array of strings? An array of bson.ObjectID? Or an Array of OrderModel?
         Orders  []string        `json:"orders" bson:"orders"`
         Orders  []bson.ObjectId `json:"orders" bson:"orders"`
         Orders  []OrderModel    `json:"orders" bson:"orders"`
         ...
    }
)

func (user *UserModel) PopulateOrders() {
    orders := []OrderModel{}

    // Query orders and assign to variable orders to then be assigned the the user Object
    // {magic query here}

    user.Orders = orders
}

In MongoDB, an array of ObjectIDs would be stored to reference the OrderModel documents. Later on, I have a function that will populate the Order documents like described above: PopulateOrders.

What is the best way for the case above?

Upvotes: 2

Views: 89

Answers (1)

icza
icza

Reputation: 417662

I would use 2 separate fields, one for the slice of IDs, and one for the slice of lazily loaded objects.

Omit the lazily loaded object slice from saving. It could look like this:

type UserModel struct {
     // ...
     OrderIDs []bson.ObjectId `json:"orderIDs" bson:"orderIDs"`
     Orders   []OrderModel    `json:"orders" bson:"-"`
     // ...
}

Note that I intentionally did not exclude Orders from JSON serialization, as it is (may) be useful in JSON representation.

Upvotes: 1

Related Questions