I can use my query to filter/search for a specific user and I'm happy with that. However, It doesn't return the correct or full amount of data that I'm expecting, as shown below. I need the bio and other fields of data to be included. Even as I tried the answer down below I'm still returning the wrong data. It must be how I'm appending the data?
type Profile struct {
Username string
Verified bool
Protected bool
Avatar string
Banner string
FollowerCount int32
FollowingCount int32
TreatCount int32
LikeCount int32
Name string
Bio string
Website string
Location string
}
func SearchProfiles(filter string) ([]models.Profile, error) {
results := []models.Profile{}
filterr := bson.D{{Key: "username", Value: primitive.Regex{Pattern: filter, Options: ""}}}
cur, err := userColl.Find(ctx, filterr)
if err != nil {
log.Fatal().
Err(err).
Msg("err1")
}
for cur.Next(context.TODO()) {
var elem models.Profile
err := cur.Decode(&elem)
fmt.Println(elem)
if err != nil {
log.Fatal().
Err(err).
Msg("err2")
}
results = append(results, elem)
}
if err := cur.Err(); err != nil {
log.Fatal().
Err(err).
Msg("err3")
}
cur.Close(context.TODO())
return results, nil
}
searchProfiles returns this:
1:
avatar: ""
banner: ""
bio: ""
followerCount: 0
followingCount: 0
likeCount: 0
location: ""
name: ""
protected: false
treatCount: 0
username: "dev"
verified: false
getProfile returns this:
...
profile:Object
username:"dev"
verified:false
protected:false
avatar:""
banner:""
followercount:163
followingcount:15
treatcount:13
likecount:612
name:"developer"
bio:"23, ayooo"
website:""
location:"afk"
CodePudding user response:
Try to add to your Profile model additional description of every parameter that you need returned from db so they match exactly. So if you have your model with parameter 'Name' and in your mongo document it's 'name' than you need to map it with 'bson'. For example:
type Profile struct {
***
Name string `json:"name" bson:"name"`
TreatCount int32 `json:"treatcount" bson:"treatcount"`
***
}
Read more here: https://www.mongodb.com/blog/post/quick-start-golang--mongodb--modeling-documents-with-go-data-structures
CodePudding user response:
It was how I was appending the data!!
func SearchProfiles(filter string) ([]models.Profile, error) {
profiles := []models.Profile{}
user := models.User{}
filterr := bson.D{{Key: "username", Value: primitive.Regex{Pattern: filter, Options: ""}}}
cur, err := userColl.Find(ctx, filterr)
if err != nil {
log.Fatal().
Err(err).
Msg("err1")
}
for cur.Next(context.TODO()) {
err := cur.Decode(&user)
if err != nil {
log.Fatal().
Err(err).
Msg("err2")
}
profiles = append(profiles, user.Profile)
}
if err := cur.Err(); err != nil {
log.Fatal().
Err(err).
Msg("err3")
}
cur.Close(context.TODO())
return profiles, nil
}