Meteor JS : Client not getting data from Mongo DB

断了今生、忘了曾经 提交于 2019-12-05 15:39:16

Cursor.fetch() returns immediately with data currently available. If no data are available on the client in the time of call, it returns nothing.

It is reactive source, so just try to call it in Tracker.autorun and it will be recomputed when the reactive source changes.

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

How to access data in Mongo DB from html ?

First of all you need to have the Mongo DB instance present in global variable i:e it must be declared in any .js file as below. It is not part of client or server code

Say we create a Collection of Events in one of the js files.

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

Now, in order to access all the objects from HTML, we would need a helper function inside client in our .js file. Below is Helper used:-

    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();
         }

    });

Just left to display all the content on .html:-

Say EventList Collection has fields Event_Name, Event_Date. Below would be the html template code

    <template name="viewEvent">
       <h2>View Event</h2>
       <!-- Iterate on all Objects fetched by the Helper Class-->
       {{#each event}}
          {{Event_Name}} : {{Event_Date}} 
       {{/each}}
   </template>

Try putting

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

into both client side and server side and see if it works?

Also try console.log(newColl.find().fetch()) in your browser console and see if it returns any data. If yes then it may be because the data is not ready yet when you print out the newColl.find().fetch().

I'm new to meteor.js(so maybe I'm wrong). I think you need to implement some methods to observe changes in collection, to avoid that when rendering pages you can use meteor template.

If you want to see a log from the client side only for "learning" purpose, just use client console from your browser.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!