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

305
Views
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 answers
Answer question

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 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!