2015-04-17 26 views
3

鑑於我有3種類型的集合和一個動態值,我將如何根據該動態值指定要搜索的集合?你會如何在Meteor中找到一個具有價值的動態集合?

E.g,

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

你應該得到我一輩子的啤酒。我欠你。 P.我想我們在SF中曾經在流星聚會上遇到過。我一定會在這座城市給你買一瓶啤酒:) –

+0

所以,要說明這一點,重要的一點是'return this [capitalize(name)+'s'];',這表明聲明的集合只是一個應用程序的屬性('this'),對嗎? –

+0

@DanielFischer哈哈我會接受! :) –

相關問題