Reference collection name in variable

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

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

1 Like

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

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

2 Likes

This thread is Google Indexed pretty high. So adding an update.

Declaring a collection globally seems to bring some security considerations.

This package allows for collections to be interacted with by collection name: https://atmospherejs.com/dburles/mongo-collection-instances

…And by the way…2015…buy BitCoins!!

1 Like