Collection undefined at startup

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 =;
            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?


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')


export const Count = new Mongo.Collection('count');

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) { 
   const a = Count.find().count();

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:

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:

  1. Pass an onReady callback to the subscription:
Meteor.subscribe('count', function() {
   const a = Count.find().count();
  1. Use an autorun:
Tracker.autorun(function () {
   const a = Count.find().count();

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();
1 Like