How to check if an Collection exists?

Is there a best practice to avoid “undefined” errors when checking a collection, or other objects.

Example:

var existingCollection = MyCollection.find({field: value}).count();

if (existingCollection > 0)
do it

// But if MyCollection has not been created yet the existingCollection would be “undefined”

Someone could do:

if ( typeof existingCollection === ‘undefined’)
do something else

Is there a best practice of handling this?

THX

Hi,

I use a dodgy fix. Set a session: Session.set(‘loaded’, ‘0’); and then have a check in the template so it shows Loading or something. Can link this up to whatever is loading in the JS also.

Not sure that this helps, but just my 2c.

Tat

Yeah that maybe would work on client. But any idea on the server side? thx

There’s nothing async happening on the server. Just define your collections before you start querying them.

Are you sure this isn’t a load order problem?

Well the collection is defined like so in lib/collection.js
MyCollection = new Mongo.Collection(“example”);

But the Collection doesn’t exist until you insert some data,
or am I wrong here?

You can query an empty collection, no problem. You’ll just get an empty array when you find().fetch() or null when you .findOne().

The actual mongodb collection isn’t created until you insert some data, but that doesn’t stop you from creating and querying an empty Meteor Mongo collection (which gives a nice programmatic wrapper for the actual mongodb collection).

Yes I was able to reproduce that. No idea what caused this “undefined” issue. I did a meteor reset. And tried it again and I get back a result. Thats cool I just have to get rid of my if (typeof collection = “undefined”) structures :slightly_smiling:
Thanks awesome. I found this article as well. https://blog.serverdensity.com/checking-if-a-document-exists-mongodb-slow-findone-vs-find/

Would you agree on that? Thank you alot dude

Interesting article. I hadn’t thought about that before. Although I don’t really do enough reads in my apps to feel much of a performance hit due to that yet. (Not enough users! :yum:)

:slight_smile: Well someday that will change

On client side:
Meteor.connection._mongo_livedata_collections
or
Meteor.connection._stores

1 Like