4

I would like to iterate over multiple Mongo collections in meteor (server side). First I would like to check if a collections has any documents.

My code so far:

     var isEmptyCollection = function(name) {
          if(name.find().count() === 0) {
             return true
          } else {
             return false
          }
        };

        var mycollections = ["CollectionOne", "CollectionTwo", "CollectionThree"];


        for (var i = 0; i < mycollections.length; i++) {
            if (isEmptyCollection(mycollections[i])) {
        } else {
            var data = mycollections[i].find({},{fieldOne: 1}).fetch();
            console.log(data);
        }

I get this Error:

    TypeError: Object CollectionOne has no method 'find'....

How can I iterate over collections / check in a loop if a collection has any values?

1

2 Answers 2

1

Your array of collections contains a lot of strings, but it should contain a list of collection objects. Try changing the array assignment to:

var mycollections = [CollectionOne, CollectionTwo, CollectionThree];

I'm assuming you've defined these using Mongo.Collection.

1
  • Yes those are Mongo.Collections. Thank you. That solved the problem! Jun 9, 2015 at 8:52
1

mycollections[i] would be the string "CollectionOne". Use global[ mycollections[i] ] to get a reference to the actual collection.

E.g: global[ mycollections[i] ].find().count()

On the client window[ mycollections[i] ] would be it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.