2016-07-05 143 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"` 
    } 

現在它按預期工作!