[英]Meteor: No docs from remote collection in template helper when connecting two apps via DDP
通過DDP.connect連接兩個Meteor應用程序需要以下步驟(據我所知):
我有兩個應用程序(其中一個遠程程序直接連接到MongoDB,另一個較小的程序可以處理所有前端交互)。 我可以成功地通過(步驟2和3-代碼位於_connect.js文件中的lib
文件夾中,以確保在該文件夾中的任何其他代碼之前執行該代碼)進行連接:
if (Meteor.isServer) {
if (process.env.NODE_ENV === 'development') {
// development environment
worker_host = 'localhost:4000'; // ip address of job worker host
// connect to job worker
remote = DDP.connect(worker_host);
}
remote.subscribe('cards', function() {
console.log('Number of docs: ' + Cards.find().count());
});
}
當我隨后使用remote.subscribe
時,它還會顯示期望的文檔數。 這是代碼中唯一顯示正確文檔數量的地方,其他所有地方都顯示0。
卡收集通過以下步驟(步驟1)正確發布在遠程服務器(在端口4000上運行)上:
Meteor.publish('cards', function() {
return Cards.find()
});
步驟4:我不確定該代碼的確切位置。 它當前位於lib
文件夾中,因此該集合在客戶端和服務器上都是已知的:
Cards = new Mongo.Collection('cards',remote);
console.log('Number of docs: ' + Cards.find().count());
執行此代碼時,它始終顯示0個文檔。
但是,當我想訪問模板幫助器中的相同(遠程)集合時(步驟5-文件位於client
文件夾中):
Template.puzzle.helpers({
cards: function() {
console.log('Number of docs: ' + Cards.find().count());
return Cards.find();
}
});
在幫助程序代碼中找不到單個文檔。
由於上述原因,html模板(也位於client
文件夾中) 未顯示任何內容 :
<template name="puzzle">
<div class="container">
{{#each cards}}
// lot's of <div> displaying the content of the cards doc
{{/each}}
</div>
</template>
顯然,我一定忽略了一些非常簡單的內容,我懷疑這是放置相關代碼的地方。
我需要更改上述代碼的哪些步驟才能訪問遠程集合? 我檢查了通常的來源(SO,Meteor論壇),但是找不到用於連接兩個應用程序的推薦結構。
PS:我已經閱讀了使用DDP連接兩個Meteor應用程序
確實,正確的方法確實是@Robert Simon所建議的,並決定僅在服務器上還是僅在客戶端上運行它。 由於我需要通過客戶端顯示集合的內容,因此所有內容都必須移至客戶端。
這些是使其生效的編輯:
步驟2/3(將_connect.js文件移動到client
文件夾:
worker_host = 'localhost:4000'; // ip address of job worker host
// connect to job worker
remote = DDP.connect(worker_host);
remote.subscribe('cards', function() {
console.log('Number of cards1: ' + Cards.find().count());
});
步驟4(將cards.js文件移至client
文件夾:
Cards = new Mongo.Collection('cards',remote);
第一次執行puzzle.js文件(幫助程序)時,由於應用程序運行得如此之快,因此它不會顯示任何卡片,因此沒有發生通過DDP進行數據傳輸的情況。 在隨后的第二次運行中,所有文檔都將在幫助器中接收並顯示在html文件中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.