There are times when you are writing a Meteor application where you would like to use Mongo syntax to store and access data on your client – but you don’t really want to store that data on the server.

Local Collections in Mongo

There is a really quick approach you can take is to just use mini-Mongo using a specific syntax for making your collection client side only:

var myClientOnlyCollection = new Mongo.Collection(null);

Now there is a caveat to this local collection:

  1. Data is lost when the user refreshes the page
  2. Data is not synced between open tabs on the same machine
  3. You can only have one local Mongo collection, if you make many instances of new Mongo.Collection(null), they all show the same data.

Beyond Mongo

Alright, so how do we overcome all this little nuances that a local Mongo collection gives us? Well, we can use GroundDB. You can add it to your Meteor project by running:

meteor add ground:db

Now we can use GroundDB instead of MongoDB. Don’t worry, GroundDB just adds a transparent layer on top of your MongoDB.

So, we can define a Mongo Collection that syncs data into the browser’s localstorage. It will pull that localstorage data when the collection is created. That takes care of problems #1 and #2. Here’s the code:

Ground.Collection(null);

But what about problem #3? Well, we need to give our collection a name, but we also need to make sure it is still local. Luckily, GroundDB allows us to do that:

Ground.Collection('todos', {connection: null});

Awesome!

We now have a collection that is:

  1. Local to the user’s browser
  2. Not synced with the Server
  3. Stores data to localstorage
  4. Listens for changes to the localstorage
  5. “Namespaced” – we don’t have to worry about our local collections clashing with each other