Reputation: 1677
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?
Upvotes: 4
Views: 237
Reputation: 1091
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.
Upvotes: 1
Reputation: 4703
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
.
Upvotes: 1