How would you find a collection dynamically in Meteor with a value?

被刻印的时光 ゝ 提交于 2019-12-29 07:15:23

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/29690350/how-would-you-find-a-collection-dynamically-in-meteor-with-a-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!