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.
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)
}
CodePudding user response:
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"`
}