3

Given I have 3 types of collections and a dynamic value, how would I specify what collection to search for based on that dynamic value?

E.g,

array = [
  {id: 'one', type: 'profile'},
  {id: 'something', type: 'post'},
  {id: 'askjdaksj', type: 'comment']
]

How would I isolate the type and turn it into a collection? Basically turning type into Collection.find

array[0].type.find({_id: id});
=> Profiles.find({_id: id});

Is this possible?

Daniel Fischer
  • 3,042
  • 1
  • 26
  • 49

1 Answers1

6

Here's a complete working example:

Posts = new Mongo.Collection('posts');
Comments = new Mongo.Collection('comments');

var capitalize = function(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
};

var nameToCollection = function(name) {
  // pluralize and capitalize name, then find it on the global object
  // 'post' -> global['Posts'] (server)
  // 'post' -> window['Posts'] (client)
  return this[capitalize(name) + 's'];
};

Meteor.startup(function() {
  // ensure all old documents are removed
  Posts.remove({});
  Comments.remove({});

  // insert some new documents
  var pid = Posts.insert({text: 'I am a post'});
  var cid = Comments.insert({text: 'I am a comment'});

  var items = [
    {id: pid, type: 'post'},
    {id: cid, type: 'comment'}
  ];

  _.each(items, function(item) {
    // find the collection object based on the type (name)
    var collection = nameToCollection(item.type);

    // retrieve the document from the dynamically found collection
    var doc = collection.findOne(item.id);
    console.log(doc);
  });
});

Recommended reading: collections by reference.

David Weldon
  • 63,632
  • 11
  • 148
  • 146
  • 1
    You deserve a lifetime of beers from me. I owe you. P.s I think we met at a Meteor meetup once in SF. I'll definitely buy you a beer in the city :) – Daniel Fischer Apr 17 '15 at 06:26
  • So, to distill this down, the important point is `return this[capitalize(name) + 's'];` , which shows that a declared collection is just a property of the app (`this`), correct? – Andrew Shooner Apr 17 '15 at 13:40
  • @AndrewShooner Yes - because collections are nearly always declared as global to the app, we are looking for `this[collectionName]` where `collectionName` is determined somehow (it this case it was a combination of pluralization and capitalization, but it depends on your situation). – David Weldon Apr 17 '15 at 17:08