问题
I have started learning MeteorJS and made a sample app. I have a collection in mongoDB and I am trying to see that collection in client Here is my server Code(file is in /libs)
newColl=new Meteor.Collection("newColl");
if(Meteor.isServer){
Meteor.publish('newCollectionData', function(){
console.log(newColl.find().fetch());
return newColl.find();
});
}
Here is My client Code(file is in /client)
Meteor.subscribe("newCollectionData");
//console.log(newColl.find());
console.log(newColl.find().fetch());
var data= newColl.find().fetch();
console.log(data);
The log in server prints the data correctly but the log on client prints an empty array. PS: I have removed auto publish, but with it also it was giving same result. Where am I going Wrong?
回答1:
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());
});
回答2:
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>
回答3:
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().
回答4:
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.
来源:https://stackoverflow.com/questions/26225685/meteor-js-client-not-getting-data-from-mongo-db