我已經購買了發現流星書並通過了本教程。我仍然不確定幾個部分,並遇到了一個我無法工作的問題。如何從Meteor的不同集合中的特定字段返回值?
我有兩個集合。
Computers = new Mongo.Collection('computers');
Apps = new Mongo.Collection("apps");
在我發佈的服務器:
Meteor.publish('computers', function() {
return Computers.find();
});
Meteor.publish('apps', function() {
return Apps.find();
});
在客戶訂閱使用鐵路由器:
Router.configure({
waitOn: function() {
return [Meteor.subscribe('computers'),
Meteor.subscribe('apps'),
Meteor.subscribe('users')];
}
});
在一個集合我已經引用的文件與另一個文件的ID在另一個集合中。
Computers.insert({
_id: sd9f9sdf699,
name: 'Mac1'
});
Apps.insert({
_id: ewf4y34349f,
name: 'App One',
version: '1.0',
computerId: sd9f9sdf699
});
然後我使用的是{{#each}}塊通過在應用程序集合中的文件進行迭代
{{#each apps}}
{{> appItem}}
{{/each}
<template name="appItem">
<tr>
<td><input type="checkbox" name="checked" class="ui checkbox"></td>
<td>{{name}}</td>
<td>{{version}}</td>
<td>{{computerName}}</td>
</tr>
</template>
,當我到了computerId領域,我想匹配在計算機集合中記錄文件,然後返回計算機的名稱而不是id。
這裏是我的app_item.js代碼:
Template.appItem.helpers({
computerName: function() {
var id = this.computerId;
var compName = Computers.find({_id: id}, {fields: {name: 1} }).fetch();
return compName;
}
});
我顯然失去了一些東西,但我似乎無法環繞它是什麼我的頭。
如果可能,我會更喜歡一個答案,會教我什麼,我做錯了,而不是一個副本&粘貼解決方案如何解決它。我似乎有一個理解這個問題,並會感謝任何意見什麼編程理論,我應該審查。
感謝您的閱讀! Piotr
謝謝你的回答。我寧願讓它與單獨的集合一起工作,因爲我在應用程序的其他部分也遇到同樣的問題,例如將計算機分配給用戶,將附件(例如pdf)分配給應用程序,用戶或計算機。我也明白,這不是像Mongo這樣的數據存儲的理想方式,但我決定學習Meteor而不是使用Rails + SQL路線。爲了縮短這篇文章,我還削減了很多代碼。 Console.log(compName)返回一個對象。然後,我也嘗試使用{{computerName.name}},但也沒有工作。 –
好的,既然它是一個對象,你必須通過循環來獲得你需要的值,但是因爲它總是隻有1個結果,所以你可以使用findOne作爲他在答案中提到的Tomas,只返回1個結果作爲數組並返回。 – kiewietr