morsecoder
morsecoder

Reputation: 1659

Is Reactivity in Meteor affected by the fields selected in the query?

If my UI depends on

MyCollection.find({_id: "..."})

I know that it triggers the reactivity whenever any field in that document changes. But if I just select one field from that document:

MyCollection.find({_id: "..."}, {fields: { MyAttr: 1 }})

Does reactivity get triggered for any change to the document with that _id, or does it only get triggered for changes to the MyAttr field of that document?

Upvotes: 1

Views: 64

Answers (1)

morsecoder
morsecoder

Reputation: 1659

I made a simple test to determine this:

test.html:

<template name="test">
  {{ #if Template.subscriptionsReady }}
    {{ GetMyAttr }}
  {{ /if }}
</template>

test.js:

Template.test.helpers({
  GetMyAttr: function() {
    console.log('called GetMyAttr');
    return MyCollection.findOne({_id: "jpBLBgCyEi3XpicxF"}).MyAttr;
  }
});

Template.test.onCreated(function() {
  this.subscribe("my_collection");
});

Now, when I manually update MyOtherAttr on the "jpBLBgCyEi3XpicxF" document, called GetMyAttr is logged to the console. But if I change the find statement to:

return MyCollection.findOne({_id: "jpBLBgCyEi3XpicxF"}, {fields: {MyAttr: 1}}).MyAttr;

Then updating the MyOtherAttr on the "jpBLBgCyEi3XpicxF" document does not cause called GetMyAttr to be printed.

Conclusion: Cursors react only to changes in the data returned in those cursors.

In retrospect, this seems obvious that it should work that way. I think this is a good reason to use the {fields: {}} part of the query more often, to reduce unnecessary reactivity.

Upvotes: 1

Related Questions