你如何在Meteor中动态找到一个具有值的集合?

时间:2015-04-17 04:30:50

标签: meteor

鉴于我有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});

这可能吗?

1 个答案:

答案 0 :(得分: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