我可以使用我的查询来过滤/搜索特定的用户,我对此很满意。但是,它没有返回我期望的正确或完整的数据量,如下所示。我需要的传记和其他领域的数据被包括在内。即使我尝试了下面的答案,我仍然返回了错误的数据。这一定是我追加数据的方式?
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返回以下内容:
1:
avatar: ""
banner: ""
bio: ""
followerCount: 0
followingCount: 0
likeCount: 0
location: ""
name: ""
protected: false
treatCount: 0
username: "dev"
verified: falsegetProfile返回以下内容:
...
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"发布于 2021-09-15 08:13:23
这就是我追加数据的方式!
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
}发布于 2021-09-14 11:01:44
尝试向您的配置文件模型添加您需要从db返回的每个参数的额外描述,以便它们完全匹配。因此,如果你的模型带有参数'Name‘,并且在mongo文档中是'name’,那么你需要用'bson‘来映射它。例如:
type Profile struct {
***
Name string `json:"name" bson:"name"`
TreatCount int32 `json:"treatcount" bson:"treatcount"`
***
}https://stackoverflow.com/questions/69175590
复制相似问题