[英]Easiest way to get Json / Collection through Meteor Iron Router
例如,我正在創建一組路線
/
-應該呈現主頁模板
/items
應該項目頁面模板
/items/weeARXpqqTFQRg275
應該從MongoDB返回具有給定_id的項目
這是我正在努力實現的示例
Router.route('items/:_id', function () {
var item = return myItems.find(:_id);
this.render(item);
});
[更新-解決]通過在服務器端使用Router.map
而不是Router.route
解決了此問題
Router.map(function () {
this.route('post', {
path: 'items/:_id',
where: 'server',
action: function(){
var id = this.params._id;
var json = myItems.findOne({_id: id});
this.response.setHeader('Content-Type', 'application/json');
this.response.end(JSON.stringify(json, null, 2));
}
});
});
您的代碼有幾個問題。
首先,您似乎想從url獲取_id
參數,卻不知道如何。 它存儲在this.params
,所以它是this.params._id
。
其次,你應該發送給第一個參數find
是MongoDB中查詢你的情況是{ _id: this.params._id }
第三,這不是您在Iron Router中渲染內容的方式。 render方法上的string參數是要渲染的模板的名稱 ,而不是項目的名稱。
假設myItems
是有效的集合,並且您的模板名為showItem
,則您的代碼應類似於:
Router.route('items/:_id', {
name: 'showItem',
data: function () {
return myItems.find({ _id: this.params._id });
}
});
嘗試這樣的事情:
Router.map(function () {
this.route('items/:myItemId', {
data: function(){
return myItems.findOne({_id: this.params.myItemId});
}
});
});
祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.