当前位置: 动力学知识库 > 问答 > 编程问答 >

Get Meteor collection by name

问题描述:

Suppose I write:

new Meteor.Collection("foos");

new Meteor.Collection("bars");

Is there an API for accessing those collections by name? Something like Meteor.Collection.get(name), where name is "foos" or "bars"? I know I could write something like

var MyCollections = {

foos: new Meteor.Collection("foos");

bars: new Meteor.Collection("bars");

}

and then use MyCollections[name], but I'd prefer to use an existing API if one exists.

网友答案:

As far as I can see in the collection.js source there currently is no way in the api to get an existing Collection by name, once it has already been initialized on the server. It probably wouldn't be hard to add that feature.

So, why not fork Meteor and submit a patch or create a smart package and share it I'm sure there are others out there who'd like the same feature.

网友答案:

Based on Shane Donelley's mongoinspector https://github.com/shanedonnelly1/mongoinspector

getCollection = function (string) {
for (var globalObject in window) {
    if (window[globalObject] instanceof Meteor.Collection) {
        if (globalObject === string) {
            return (window[globalObject]);
            break;
        };        
    }
}
return undefined; // if none of the collections match
};
网友答案:

I've just found that package : https://github.com/dburles/mongo-collection-instances/

It allow you to

Foo1 = new Mongo.Collection('foo'); // local
Foo2 = new Mongo.Collection('foo', { connection: connection });

Mongo.Collection.get('foo') // returns instance of Foo1

Mongo.Collection.get('foo', { connection: connection }); 
// returns instance of Foo2

Hope it will help

网友答案:

This feature was added to Meteor in Feb 2016: "Provide a way to access collections from stores on the client"

It works like this:

Meteor.connection._stores['tasks']._getCollection();

And I was using it as follows to test inserts using the javascript console:

Meteor.connection._stores['tasks']._getCollection().insert({text:'test'});

For the insert it required the insecure package to still be installed otherwise got an access denied message.

网友答案:

With https://github.com/dburles/mongo-collection-instances you can use Mongo.Collection.get('collectionname')

Note that the parameter you're inserting is the same one you use when creating the collection. So if you're using const Products = new Mongo.Collection('products') then you should use get('products') (lowercase).

网友答案:

Rather than looking, I've just been doing:

Foos = new Meteor.Collection("foos");

or possibly put it inside another object. I haven't really been making a Collections collection object.

网友答案:

Note that they have a return value, so you can just do

var Patterns = new Meteor.Collection("patterns");

and use Patterns everywhere.

And when you need to subscribe to server updates, provide "patterns" to Meteor.subscribe().


If you have the same code for multiple collections, the chance is high that you're doing something wrong from a software engineering viewpoint; why not use a single collection with a type field (or something else that differentiates the documents) and use that instead of using multiple collections?

网友答案:

It seems there is no way to get at the wrapped Meteor.Collection object without saving it at creation time, as others have mentioned.

But there is at least a way to list all created collections, and actually access the corresponding Mongo LocalCollection object. They are available from any Meteor Collection object, so to keep it generalistic you can create a dummy collection just for this. Use a method as such (CoffeeScript):

dummy = new Meteor.Collection 'dummy'
getCollection = (name) ->
  dummy._driver.collections[name]

These objects do have all the find, findOne, update et al methods, and even some that Meteor doesn't seem to expose, like pauseObservers and resumeObservers which seem interesting. But I haven't tried fiddling with this mongo LocalCollection reference directly to knowif it will update the server collection accordingly.

网友答案:
var bars = new Meteor.Collection("foos");

Judging by what the collection.js does, the line we use to instantiate the collection object opens a connection to the database and looks for the collection matching the name we give. So in this case a connection is made and the collection 'foos' is bound to the Meteor.Collection object 'bars'. See collection.js AND remote_collection_driver.js within the mongo-livedata package.

As is the way with MongoDB, whilst you can, you don't have to explicitly create collections. As stated in the MongoDB documentation:

A collection is created when the first document is inserted.

So, I think what you're after is what you already have - unless I've totally misunderstood what you're intentions are.

网友答案:

Anyone come up with a solution for this? It'd be great to be able to do this:

Handlebars.registerHelper('getCollection', function(e) {
 return Meteor.collection(e) // or something like this
});

and have template code like

  {{#each getCollection 'myCollection' }}

That would be really useful as I have noticed some redundancies doing it w/ meteor template helpers...

网友答案:

You can always roll your own automatic collection getter.

Say you have a couple of collections called "Businesses" and "Clients". Put a reference each into some "collections" object and register a Handlebars helper to access those "collections" by collections["name"].

i.e. put something like this on the client-side main.js:

collections = collections || {};
collections.Businesses = Businesses;
collections.Clients = Clients;

Handlebars.registerHelper("getCollection", function(coll) {
  return  collections[coll].find();
});

Then in your HTML, just refer to the collection by name:

{{#each getCollection 'Businesses'}}
  <div> Business: {{_id}} </div>
{{/each}}

{{#each getCollection 'Clients'}}
  <div> Client: {{_id}} </div>
{{/each}}

Look ma, no more generic "list all records" boilerplate js required!

分享给朋友:
您可能感兴趣的文章:
随机阅读: