1
我试图获取某个用户创作的博客条目列表,但我的查询只返回创建的第一个条目。Golang mgo查询只返回查询中的第一个对象
这是我的用户模型
type User struct {
Id bson.ObjectId `bson:"_id,omitempty" json:"id"`
Name string `json:"name"`
}
和我BlogEntry模型
type BlogEntry struct {
Id bson.ObjectId `bson:"_id,omitempty" json:"id"`
UserId bson.ObjectId `json:"user_id"`
Title string `json:"title"`
}
这是我用来获取所有博客条目针对特定用户
iter := service.Collection.Find(bson.M{"user_id": bson.ObjectIdHex(id)}).Iter()
问题是查询,这只会导致带有传入ID的用户的第一个条目。
我检查了数据,看起来是正确的,所有条目都有一个正确的user_id字段,依此类推。
任何想法,为什么我只得到第一个条目?
编辑:
完全实现我的功能是查询条目。
func (service *BlogEntryService) GetEntryByUserId(id string) []models.BlogEntry {
var entries []models.BlogEntry
iter := service.Collection.Find(bson.M{"user_id": bson.ObjectIdHex(id)}).Iter()
result := models.BlogEntry{}
for iter.Next(&result) {
entries = append(entries, result)
}
return entries
}
显示您用来遍历条目的代码。 –
@XyMcXface当然,更新了这篇文章。 – marsrover
在循环之后调用iter.Close()并报告返回的错误(如果有的话)。另外,你可以把它写成'err:= service.Collection.Find(bson.M {“user_id”:bson.ObjectIdHex(id)})。Iter()。All(&entries)'。 –