2015-04-17 1 views
3

Учитывая, что у меня есть 3 типа коллекций и динамическое значение, как бы я определил, какую коллекцию искать на основе этого динамического значения?Как вы находите коллекцию динамически в Метеор со значением?

например,

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

Как бы выделить тип и превратить его в коллекцию? В основном токарный тип в Collection.find

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

Возможно ли это?

+0

Это может помочь: http://stackoverflow.com/questions/6084858/javascript-use-variable-as-object-name –

ответ

5

Вот полный рабочий пример:

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); 
    }); 
}); 

Рекомендуемая литература: collections by reference.

+0

Вы заслуживаете всю жизнь пива от меня. Я у тебя в долгу. П. Я думаю, что мы встретились в Метеорской встрече однажды в СФ. Я обязательно куплю вам пиво в городе :) –

+0

Итак, чтобы отделить это, важным моментом является 'return this [capizeize (name) + 's'];', который показывает, что заявленная коллекция - это просто свойство приложения ('this'), правильно? –

+0

@ DanielFischer Ха-ха, я возьму! :) –