Meteor JS:客户端没有从Mongo DB获取数据

Meteor JS : Client not getting data from Mongo DB

本文关键字:Mongo DB 获取 数据 JS 客户端 Meteor      更新时间:2023-09-26

我已经开始学习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);

登录服务器会正确打印数据,但登录客户端会打印一个空数组。附言:我已经删除了自动发布,但它也给出了同样的结果。我错在哪里?

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

它是无功电源,所以只需尝试在Tracker.autorun中调用它,当无功电源发生变化时,它将被重新计算。

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

如何从html访问MongoDB中的数据

首先,您需要在全局变量i:e中提供MongoDB实例,它必须在任何.js文件中声明,如下所示它不是客户端或服务器代码的一部分

假设我们在其中一个js文件中创建了一个事件集合。

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

现在,为了从HTML访问所有对象,我们需要在.js文件中的客户端中使用一个helper函数。下面是使用的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>

尝试放置

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

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

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

时,数据还没有准备好

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

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