Reference collection name in variable


#1

For example:

client/lib/helpers.js

// say selected_collection = "cat_names"
var collection_name = Session.get("selected_collection");

// get all docs in collection
return collection_name.find();

What’s the correct way to do that?

Thanks


#2

If you declared your collection globally:

// Client
window[collection_name].find()

// Server
global[collection_name].find()

or

this[collection_name].find()

where this is the context outside of any functions

// Store context of this in "outside" variable
var outside = this;
function () {
  outside[collection_name].find();
}

Using this is handy because it works on both client ({window}) & server ({global})


#3

Thanks @TwinTails . It seems I’m running in to a slightly more complicated situation. Basically, I developed two Meteor packages that I’ve installed into my Meteor application. Each package has a log collection that I am trying to query from the Meteor Application. However, it seems I am unable to connect to those collections:

// pkg_1_log is defined in pkg_1 package.
pkg_1_log.find().count();
ReferenceError: Can't find variable: pkg_1_log

// pkg_2_log is defined in pkg_2 package.
pkg_2_log.find().count();
ReferenceError: Can't find variable: pkg_2_log

What do I need to tweak in order for that to work?

Thanks


#4

When accessing these variables outside of any packages:
pkg_1 package:

// package.js
api.export("pkg_1_log");

pkg_2 package:

// package.js
api.export("pkg_2_log");

http://docs.meteor.com/#/full/pack_export