mongodb - Golang mgo 查询只返回查询中的第一个对象

标签 mongodb go 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
    }

最佳答案

好吧,我想通了,可能是初学者的错误。

我仍然不知道为什么它会返回第一个对象,这还是有点奇怪。

但我的错误是没有在模型上添加“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/

相关文章:

php - 如何单击表条目并在另一个 mongodb 集合(php/jquery)中搜索它

MongoDB 存储 ObjectId 的数组

go - 如何从 Go 库中获取对象构建信息?

mongodb - 如何在带有库mgo的golang中使用$ facet?

c# - MongoDB:如何在 C# 中使用嵌套数组加载集合?

javascript - 如何知道 Mongoose 的 upsert 是否创建了新文档?

web-services - Gin 通配符路由与现有子项冲突

go - Go 中的解码返回空白输出

mongodb - 如何使用golang在mongodb中插入多数组

mongodb - 使用golang从MongoDB批量获取记录