Sophie McCarrell
Sophie McCarrell

Reputation: 2871

How do I access a collection from more than one file in Meteorjs?

In my main js file I have defined a "new Meteor.Collection("Decks")" and I populate some data if there is no data.

Now I have a views folder in the client folder that has the javascript for events of the templates. Each template has it's own js file. Those events need to query and update the Decks collection, but I have no idea how I would do that. I tried writing a "new Meteor.Collection("Decks")" in the event code, but I got an error that the collection already exists.

I could imagine using requirejs to pass along a global variable to the events perhaps, but I feel there must be a native way to do it in Meteor.

How do I access the same collection in a different file?

As an example, my app is called "builder", so the main js is called "builder.js" and contains:

var Decks = new Meteor.Collection("Decks");

Then I have another javascript file called "do_other_stuff.js" in the client folder and it wants to query the Decks collection, so something like:

var first_deck = Decks.findOne({name: "first"});

But obviously that won't work, because Decks is not a global variable.

Upvotes: 1

Views: 199

Answers (2)

Hubert OG
Hubert OG

Reputation: 19544

Simply, make Decks a global variable! Remove the var keyword:

Decks = new Meteor.Collection("Decks");

Upvotes: 2

Mariusz Ciesla
Mariusz Ciesla

Reputation: 129

Meteor.subscribe("Decks") in the file should do the trick.

Upvotes: 0

Related Questions