您将如何在 Meteor 中动态查找具有值的集合? [英] How would you find a collection dynamically in Meteor with a value?
本文介绍了您将如何在 Meteor 中动态查找具有值的集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于我有 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?
例如,
array = [
{id: 'one', type: 'profile'},
{id: 'something', type: 'post'},
{id: 'askjdaksj', type: 'comment']
]
如何隔离类型并将其转换为集合?基本上将类型转换为 Collection.find
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});
这可能吗?
推荐答案
这是一个完整的工作示例:
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);
});
});
推荐阅读:参考收藏.
这篇关于您将如何在 Meteor 中动态查找具有值的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文