Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!