Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda