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

181
Views
How to get the data from mongodb with all the struct variables?

In this code, I am trying to access the Cardname from the MongoDB database but it is giving me an empty string. Although it prints all the variables before Cardname but does not print the variables after Cardname and Cardname itself. enter image description here

type UserCredentials struct {
    Fname      string
    Lname      string
    Email      string
    Password   string
    Phone      string
    Country    string
    State      string
    Faddress   string
    Laddress   string
    Postal     string
    Company    string
    Cardname   string
    Cardnumber string
    Expmonth   string
    Expyear    string
}

func FindCard(email, password string) {
    var uc UserCredentials
    collection := Connect.Database("eCommerce").Collection("register")
    if err := collection.FindOne(context.TODO(), bson.M{"email": email, "password": password}).Decode(&uc); err != nil {
        log.Fatal(err)
    } 
    fmt.Println(uc.Cardname)
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The mongo driver will not magically find out which document field you want to set into which struct field.

There are some "common sense" rules, such as field names matching properties (even if the first letter is not capitalized), but the field name Cardname will not be matched with the property name "card name".

You have to tell the mapping using struct tags, namely the bson struct tag (this is what the mongo-go driver uses).

For example:

type UserCredentials struct {
    Fname      string
    Lname      string
    Email      string
    Password   string
    Phone      string
    Country    string
    State      string
    Faddress   string
    Laddress   string
    Postal     string
    Company    string
    Cardname   string `bson:"card name"`
    Cardnumber string `bson:"card number"`
    Expmonth   string `bson:"expiry month"`
    Expyear    string `bson:"expiry year"`
}
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!