Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

313
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda