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

307
Visualizações
How do you use MongoDB/bson in repository pattern

Good morning,

I'm currently trying to build a REST-API project for learning purposes and want to use the repository pattern as practice.

I have a model module where I define structs to use. Like user and posts (for both I have set the ID to a string). MongoDB uses ObjectIDs as IDs though. So my current solution is converting that in the MongoDB repository awkwardly to a user/post-struct using that ObjectID and then back again to the user/post-model that the rest of the program is using.

Is there a better way to achieve that same thing without awkward struct conversions?

Here is the code for that: https://github.com/schattenbrot/mini-blog-api

Thanks in advance already for any ideas and tips I can try out.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Mongo uses the field _id as an object's id. When you insert a document without this field, mongo auto generates its own object id which is what is happening in your case. The solution is to insert your struct with the ID field marked as _id.

This can be done by adding a bson tag on your struct with _id. Mongo will use your id instead of generating one on its own. When you marshal to json, the bson tag is ignored so everything else in your application stays the same.

type Post struct {
    ID        string    `json:"id,omitempty" bson:"_id"`
    Title     string    `json:"title,omitempty" validate:"omitempty,min=3,max=40"`
    Text      string    `json:"text,omitempty" validate:"omitempty,min=5,max=700"`
    Creator   string    `json:"user,omitempty" validate:"omitempty"`
    CreatedAt time.Time `json:"created_at,omitempty"`
    UpdatedAt time.Time `json:"updated_at,omitempty"`
}
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