Array of objects as a client-side collection in Meteor

02-01-2015 (d-m-Y)

You might need to use client-side only array of objects, so you create something like this:

var persons = [
{ id: 'a1', name: 'John', age: 23 },
{ id: 'a2', name: 'Josh', age: 25 },
{ id: 'a3', name: 'Tom', age: 26 }
];

Everything is OK untill you want to search in persons array by id, name or age. You can find existing functions around the internet for this, but we have better solution in Meteor. We can use local-only Meteor Collections.

//pass null as collection name, it will create
//local only collection
Persons = new Mongo.Collection(null);
var persons = [
{ id: 'a1', name: 'John', age: 23 },
{ id: 'a2', name: 'Josh', age: 25 },
{ id: 'a3', name: 'Tom', age: 26 }
];

for (var i = 0; i < persons.length; i++) {
Persons.insert(persons[i]);
}

var tom = Persons.findOne({ name: 'Tom' });

That's all. You can just use your existing local array and insert its values into local Persons collection. This solution takes advantage of Meteor collections implementation. I love it.

← All articles | If you want to know about new blogposts you should follow @elfoslav

comments powered by Disqus