2014-10-06 79 views
4

我已經開始學習MeteorJS並製作了一個示例應用程序。我在MongoDB的集合,我想看到在客戶端 這裏說收藏是我的服務器代碼(文件是/庫)流星JS:客戶端沒有從Mongo DB獲取數據

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:我已經刪除了自動發佈,但同時它也給出了相同的結果。我在哪裏錯了?

+0

試試這個:'Meteor.subscribe( 「newCollectionData」,函數(){的console.log(newColl.find()取());});' – saimeunt 2014-10-06 22:15:09

回答

4

Cursor.fetch()立即返回當前可用的數據。如果客戶在通話時沒有數據可用,則不會返回任何數據。

它是反應性來源,因此只需在Tracker.autorun中調用它,並且它會在反應性來源發生變化時重新計算。

Tracker.autorun(function() { 
    console.log(newColl.find().fetch()); 
}); 
+1

嘗試這但仍然得到一個空陣列 – user1551574 2014-10-07 13:27:03

0

我是新來meteor.js(所以也許我錯了)。 我想你需要實現一些方法來觀察集合中的變化,以避免在渲染頁面時可以使用流星模板。

如果您只想爲了「學習」目的而從客戶端查看日誌,那麼只需從瀏覽器中使用客戶端控制檯即可。

1

嘗試把

newColl=new Meteor.Collection("newColl");  

進客戶端和服務器端,看是否可行?

另請在您的瀏覽器控制檯中嘗試console.log(newColl.find()。fetch()),看它是否返回任何數據。如果是,那麼可能是因爲打印出newColl.find()。fetch()時數據還沒有準備好。

3

如何從html訪問MongoDB中的數據?

首先,您需要在全局變量i中存在Mongo數據庫實例:e必須在任何.js文件中聲明如下。 這不是客戶端或服務器代碼

說我們在js文件之一創建活動的集合的一部分。現在

EventList = new Mongo.Collection('Events'); 

,爲了訪問與HTML中的所有對象,我們需要在我們的.js文件內客戶端的輔助功能。下面是使用助手: -

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收藏有場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>