Remove local collection onDestroyed

Hi!

I create a LocalCollection on a template by doing something like

Template.foo.onCreated(function() {
    Foos = new Mongo.Collection(null);
});

I just want to be able to delete this coll when the user leaves the page. So, something like…

Template.foo.onDestroyed(function() {
    //How do I delete 'Foos' Local Coll here?
});

How can one achieve this?

Thanks!

If you say this.foo = ... it will be “destroyed” automatically. Its just in memory so there isn’t really any distruction beyond that

2 Likes

I’d just like to add a comment in @znewsham right answer. This is necessary because you created a Global variable when you put Foos = new Mongo.Collection(null); without a JS modification as var, let or const.
Then when you use this.foos you will set a variable inside of the template scope. Thus, all variables of the template will be destroyed with it.

So the right thing to do would be

Template.foo.onCreated(function() {
    this.Foos = new Mongo.Collection(null);
});

simply prefix this. to the creation of Foos localCollection so that it is scoped to the template and automatically gets destroyed when the template does

2 Likes