我正在尝试获取某个用户撰写的博客条目列表,但我的查询仅返回创建的第一个条目。
这是我的用户模型
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
}
最佳答案
好吧,我想通了,可能是初学者的错误。
我仍然不知道为什么它会返回第一个对象,这还是有点奇怪。
但我的错误是没有在模型上添加“user_id”字段作为 bson。 所以这个:
type BlogEntry struct {
Id bson.ObjectId `bson:"_id,omitempty" json:"id"`
UserId bson.ObjectId `json:"user_id"`
Title string `json:"title"`
}
应该是:
type BlogEntry struct {
Id bson.ObjectId `bson:"_id,omitempty" json:"id"`
UserId bson.ObjectId `bson:"user_id" json:"user_id"`
Title string `json:"title"`
}
现在它按预期工作了!
关于mongodb - Golang mgo 查询只返回查询中的第一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38211341/