[英]Meteor JS : Client not getting data from Mongo DB
我已經開始學習MeteorJS並制作了一個示例應用程序。 我在mongoDB中有一個集合,我試圖在客戶端看到該集合這是我的服務器代碼(文件在/ libs中)
newColl=new Meteor.Collection("newColl");
if(Meteor.isServer){
Meteor.publish('newCollectionData', function(){
console.log(newColl.find().fetch());
return newColl.find();
});
}
這是我的客戶端代碼(文件在/客戶端)
Meteor.subscribe("newCollectionData");
//console.log(newColl.find());
console.log(newColl.find().fetch());
var data= newColl.find().fetch();
console.log(data);
登錄服務器正確打印數據,但登錄客戶端打印一個空數組。 PS:我已經刪除了自動發布,但同時它也給出了相同的結果。 我哪里錯了?
Cursor.fetch()
立即返回當前可用的數據。 如果在呼叫期間客戶端上沒有可用數據,則不返回任何數據。
它是反應源,所以只需嘗試在Tracker.autorun
調用它,當反應源發生變化時,它將被重新計算。
Tracker.autorun(function () {
console.log(newColl.find().fetch());
});
如何從html訪問Mongo DB中的數據?
首先,您需要將Mongo數據庫實例存在於全局變量i中:它必須在任何.js文件中聲明,如下所示。 它不是客戶端或服務器代碼的一部分
假設我們在其中一個js文件中創建了一個事件集合。
EventList = new Mongo.Collection('Events');
現在,為了從HTML訪問所有對象,我們需要在.js文件中的客戶端內部使用輔助函數。 以下是Helper使用: -
Template.viewEvent.helpers ({
//NOTE : 'event' is the name of variable from html template
'event' : function () {
//returns list of Objects for all Events
return EventList.find().fetch();
}
'users' : function () {
//returns reference to Document for all users
return UserList.find().fetch();
}
});
剛剛離開以顯示.html上的所有內容: -
假設EventList Collection包含字段Event_Name,Event_Date。 下面是html模板代碼
<template name="viewEvent">
<h2>View Event</h2>
<!-- Iterate on all Objects fetched by the Helper Class-->
{{#each event}}
{{Event_Name}} : {{Event_Date}}
{{/each}}
</template>
試試看
newColl=new Meteor.Collection("newColl");
進入客戶端和服務器端,看看它是否有效?
還可以在瀏覽器控制台中嘗試console.log(newColl.find()。fetch()),看看它是否返回任何數據。 如果是,則可能是因為當您打印出newColl.find()。fetch()時數據尚未就緒。
我是meteor.js的新手(也許我錯了)。 我認為你需要實現一些方法來觀察集合中的變化,以避免在渲染頁面時你可以使用流星模板。
如果您只想從客戶端查看日志以用於“學習”目的,只需使用瀏覽器中的客戶端控制台即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.