I cannot access a collection that is supposed to be available at startup.
In lib/collection.js I have the following code.
Count = new Mongo.Collection('count');
if (Meteor.isServer) {
Meteor.startup(function() {
if(Count.find().count() === 0){ // if collecton is empty initialize to 0
Count.insert({index : 0});
}
else {
var oldState = Count.find().fetch()[0];
var id = oldState.id;
var index = oldState.index;
var newState = index + 2;
Count.update({_id: id}, {$set: {index: newState}});
}
})
};
and then on the server I have
import { Count } from '/lib/collection';
Meteor.publish('count', function() {
return Count.find();
});
but when I run the project I get “cannot read property find of undefined”…
In my template.js on the client I am using an autorun function to check that subscriptions are ready. I can access several other collections. But this particular collection does not work.
I thought files in lib were supposed to be loaded first?
Thanks
Hi @walahajj,
The issue here is that you’re importing Count
but it’s not being exported in lib/collection.js
Simply replace
Count = new Mongo.Collection('count')
with
export const Count = new Mongo.Collection('count');
2 Likes
Ok, so that fixes the “cannot read property find of undefined”. But i still have an error
I added this code to my collection.js file
if (Meteor.isClient) {
Meteor.subscribe('count');
const a = Count.find().count();
console.log(a);
}
and it successfully prints the size 0 in console. Which means my collection is never getting initialized?
But in the template.js file when I try the same thing it says ‘Count is not defined’ even though I’ve subscribed?
Edit: I figured it out. Just had toimport {Count} from 'lib/collection.js'
within my template.js file on client. ![:expressionless: :expressionless:](https://emoji.discourse-cdn.com/twitter/expressionless.png?v=5)
Thanks for your help.
The reason your count is 0 is because subscriptions are asynchronous. The data has not yet reached the client when you query the client copy of the database.
Two things you can do are:
- Pass an
onReady
callback to the subscription:
Meteor.subscribe('count', function() {
const a = Count.find().count();
console.log(a);
});
- Use an autorun:
Meteor.subscribe('count');
Tracker.autorun(function () {
const a = Count.find().count();
console.log(a);
});
Note: This will initially run without data as it’s still is sent to the client. If you want it to only run when the collection is loaded, as a test if the collection is ready:
const countSubscription = Meteor.subscribe('count');
Tracker.autorun(function () {
if (!countSubscription.ready()) return;
const a = Count.find().count();
console.log(a);
});
1 Like