How to get Collection using only collection name in Meteor 1.3?

505 Views Asked by At

In my project I'm using package which needs collection name to do some search inside collection. I just migrated into Meteor 1.3 and now this package doesn't work.

In the code package use something like:

const search = (collection_name) => {
   let collection = this[collection_name]
   ...
}

Now collection is not in global scope anymore. I could add my collection there doing global[collection_name] = Collection in my lib/collections.js, but I'd rather like to fix package to be more flexible and Meteor 1.3 compatible.

Are there any possibilities how to get Mongo Collection if you know only collection name?

4

There are 4 best solutions below

0
On BEST ANSWER

Thanks to @sashko recommendation I looked at https://github.com/dburles/mongo-collection-instances and then to lai:collection-extensions and here is how I solved it:

import { CollectionExtensions } from 'meteor/lai:collection-extensions'

let registered_collections = {}
CollectionExtensions.addExtension(function (name, options) {
  registered_collections[name] = {
    name: name,
    instance: this,
    options: options
  };
});

export function getCollectionByName(collecion_name) {
    return registered_collections[collecion_name].instance
}
1
On

Use the following technique

Meteor.default_connection._mongo_livedata_collections.users.find({}).fetch()

Just replace users with whatever collection you have.

https://forums.meteor.com/t/es6-global-collection-variables/22392/2?u=trajano

1
On

Rather than using what seems to be a private api that may change without notice as suggested by Archimedes, I recommend creating a global object to hold your collections. The meteor docs specifically state:

Generally, you'll assign Mongo.Collection objects in your app to global variables. You can only create one Mongo.Collection object for each underlying Mongo collection.

So if you have a Collections global, you can easily access the collection in question via Collections[name]. Of course you do want to limit your globals, so if you do currently have a global for your application, just give it a property to hold your collections. The following is a common pattern that you can adapt to your needs, whether your collections are located in a single file or seperately.

app = app || {};
app.collections = {
    // collections here
}
5
On

Try this magic (in client code):

Meteor.connection._stores['tasks']._getCollection()

For more info checkout:

meteor/meteor#5845 (initial attempt Dec 2015)

meteor/meteor#6160 (fixed Feb 2016)

Or if you prefer public API and don't mind another dependency use mongo-collection-instances as mentioned in the other answer.