2016-07-05 140 views
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 
    } 
+0

显示您用来遍历条目的代码。 –

+0

@XyMcXface当然,更新了这篇文章。 – marsrover

+1

在循环之后调用iter.Close()并报告返回的错误(如果有的话)。另外,你可以把它写成'err:= service.Collection.Find(bson.M {“user_id”:bson.ObjectIdHex(id)})。Iter()。All(&entries)'。 –

回答

2

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

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

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

现在它按预期工作!