SmartQuery
Getting rid of publish()
and subscribe()
SmartQuery takes your regular Collection.find()
calls, and wraps them in a special function that automatically sets up the subscription you need for you.
Demo
Using SmartQuery (Client)
Just call SmartQuery.create()
inside a regular template helper. For example:
1Template.posts.helpers({ 2 posts: function () { 3 var cursor = Posts.find({}, {limit: Session.get("postsLimit")}); 4 return SmartQuery.create("posts", cursor); 5 } 6}
SmartQuery.create(id, cursor, options)
id
: a unique id for this particular SmartQuery.cursor
: the cursor you want to use (e.g.Posts.find({}, {limit: 5})
).options
: an optional options object.
Returns an object with the following properties:
subscription
: the subscription created for this SmartQuery.cursor
: the cursor you passed to the SmartQuery.isReady()
: (function) whether the subscription is ready (Boolean).count()
: (function) returns a count of the cursor.totalCount()
: (function) returns the total count for the cursor on the server (without alimit
).hasMore()
: (function) whether there are more documents on the server (Boolean).
Defining A Security Layer (Server)
You must define a security rule on the server for each collection before data can be published to users.
SmartQuery.addRule(collection, rule)
collection
: the collection.rule
: the rule.
A rule has the following properties:
filter
: a function that, if provided, must returntrue
for every single document in the cursor. Inside the filter function, you can callthis.userId
to access the current user's_id
.fields
: an array of fields that are publishable.
Example:
1SmartQuery.addRule(Posts, { 2 filter: function (document) { 3 return document.published === true; 4 }, 5 fields: ["_id", "title", "body"] 6});
Using SubsManager
You can also use SmartQuery with SubsManager:
1var mySub = new SubsManager(); 2var options = { 3 subscribe: mySub.subscribe.bind(mySub) 4}; 5SmartQuery.create("the-id", Posts.find(), options);