【问题标题】:Meteor JS : Client not getting data from Mongo DBMeteor JS:客户端未从 Mongo DB 获取数据
【发布时间】:2014-12-01 06:30:01
【问题描述】:

我已经开始学习 MeteorJS 并制作了一个示例应用程序。我在 mongoDB 中有一个集合,我正在尝试在客户端中查看该集合 这是我的服务器代码(文件在 /libs 中)

newColl=new Meteor.Collection("newColl");
if(Meteor.isServer){
  Meteor.publish('newCollectionData', function(){
     console.log(newColl.find().fetch());
    return newColl.find();
  });
}

这是我的客户代码(文件在 /client)

  Meteor.subscribe("newCollectionData");
//console.log(newColl.find());
console.log(newColl.find().fetch());
var data= newColl.find().fetch();
console.log(data);

服务器上的日志正确打印​​数据,但客户端上的日志打印一个空数组。 PS:我已经删除了自动发布,但它也给出了相同的结果。我哪里错了?

【问题讨论】:

  • 试试这个:Meteor.subscribe("newCollectionData",function(){console.log(newColl.find().fetch());});

标签: javascript mongodb meteor client-server meteorite


【解决方案1】:

Cursor.fetch() 立即返回当前可用的数据。如果调用时客户端上没有可用数据,则不返回任何内容。

它是响应式源,所以只需尝试在Tracker.autorun 中调用它,它会在响应式源更改时重新计算。

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

【讨论】:

    【解决方案2】:

    我是新的流星.js(所以也许我错了)。 我认为你需要实现一些方法来观察集合的变化,以避免在渲染页面时可以使用流星模板。

    如果您只想从客户端查看日志以用于“学习”目的,只需使用浏览器中的客户端控制台即可。

    【讨论】:

      【解决方案3】:

      试试看

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

      进入客户端和服务器端,看看它是否有效?

      还可以在浏览器控制台中尝试 console.log(newColl.find().fetch()) 并查看它是否返回任何数据。如果是,那么可能是因为当您打印出 newColl.find().fetch() 时数据还没有准备好。

      【讨论】:

        【解决方案4】:

        如何从 html 访问 Mongo DB 中的数据?

        首先,您需要将 Mongo 数据库实例存在于全局变量中,即它必须在任何 .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 集合具有字段 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>
        

        【讨论】:

          猜你喜欢
          • 2015-06-08
          • 1970-01-01
          • 1970-01-01
          • 2015-11-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多