2016-03-28 86 views
0

訪問用戶名和profile_picture從用戶收集我已經在我的項目2個集:用戶&主題流星:由ID

在主題集合我有一個存儲的「_id」 A「createdBy」字段用戶。

*Sample object* 

{ 
    "_id": "SNj6C5fqMntSCaXdL", 
    "opic": "Best Gaming Laptop", 
    "tags": [ 
    "games", 
    "technology", 
    "product" 
    ], 
    "createdBy": "uzsMa4fZgmrrAD9ea", 
    "createdAt": "2016-03-06T21:25:38.672Z" 
} 

在用戶收集我有fields'_id」,‘名’和‘爲每一位用戶profile_picture_url’。

{ 
    "_id": "uzsMa4fZgmrrAD9ea", 
    "createdAt": "2016-03-03T03:48:05.787Z", 
    "name": "Karan Sarin", 
    "profile_picture_url": "https://pbs.twimg.com/pro2_normal.jpg" 
} 

我正在遍歷主題並顯示所有主題的列表,並且想要顯示創建者的個人資料圖片和名稱。

{{#each topics}} 
    <h2>{{topic_title}}<h2> 
    *Profile picture here* *User's name here* 
{{/each}} 

P.S.我不想在主題集合中存儲用戶的圖片和名稱。只是想在需要時從用戶的集合中訪問它們。

回答

0

也許最簡單的方法就是將名稱作爲架構的一部分,在創建時將其存儲到主題中。然後,您只需在模板中撥打{{姓名}}即可。對於您的個人資料圖片,您希望在模板中創建自定義變量。像{{getProfileImage userId}}。然後在像common.js這樣的文件中編寫一個模板助手,以便根據userId提取配置文件映像。

+0

imageURL位於用戶集合中。你能幫我解釋一下如何使用_id來獲取URL。我寫什麼代碼?謝謝。 –

0

你可以實現一個輔助函數,它返回創建主題的用戶的文檔。之後,您可以使用#with表達式將數據上下文設置爲與當前主題相對應的用戶文檔。

例如:

Template.topicsList.helpers({ 
    user: function() { 
     return Users.findOne({_id: this.createdBy}); 
    } 
}); 

<template name="topicsList"> 
    {{#each topics}} 
     <h2>{{topic_title}}<h2> 
      {{#with user}} 
       <img src="{{profile_picture_url}}" alt="{{username}}"> 
       <strong>{{name}}</strong> 
      {{/with}} 
    {{/each}} 
</template> 

請支付,您還訂閱Users收集所需文件的關注。