2014-10-06 74 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>