Golang mgo 仅查询 returns 查询中的第一个对象

Golang mgo query only returns first object in query

我正在尝试获取某个用户撰写的博客条目列表,但我的查询仅 returns 创建的第一个条目。

这是我的用户模型

 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"`
    }

现在它按预期工作了!