JoeR
JoeR

Reputation: 1913

Meteor dependencies on document vs collection

Is there a way to make a Meteor dependency on a particular subscription depend only on the documents in the collection and not the data in the documents?

For example, say I have a collection of users. I publish:

Meteor.publish("Users_All", function () {
    return Users.find();
});

On the client I have a particular dependency which is established after subscribing to the collection:

Deps.autorun(function () {
    // run some expensive computation on Users.find().fetch();
});

I only want to run my computation when a new document is added or a document is removed from the collection. However, right now it's called whenever a particular element in any document is set too. How would I structure a dependency such that this is not the case?

Upvotes: 1

Views: 152

Answers (1)

Neil
Neil

Reputation: 2147

You could manually add and remove documents from your published set, ignoring document changes.

Meteor.publish("Users_All", function () {

  var self = this;

  var handle = Users.find().observeChanges({
    added: function (id, fields) {
      self.added('users', id, fields);
    },
    removed: function (id) {
      self.removed('users', id);
    }
  });

  self.ready();

  self.onStop(function () {
    handle.stop();
  });
});

Note: The first arg to added and removed should be the name of the collection. I just assumed 'users'.

Meteor's publish docs have more information and examples.

Upvotes: 2

Related Questions