What are the benefits of using the fields option when querying in Meteor

105 views Asked by At
SomeCollection.find({}, { fields: { exerciseId: 1} })

After running a time test, it looks like this query takes longer than just find() without any arguments. Are there any benefits of limiting the field? I guess, it will use less local memory but when is that worth it?

3

There are 3 answers

1
Michel Floyd On BEST ANSWER

In my experience the benefits of using fields on the client are limited. But you should absolutely use it when defining your publications on the server for two reasons:

  1. Security: hide fields the client has no business seeing, especially fields about other users
  2. Performance: fewer fields means fewer bytes on the wire. Especially important when a subscription includes many documents.
0
Peppe L-G On

The benefit is that it becomes less reactive, which you can benefit from in Tracker.autorun and when you use observe or observeChanges.

EDIT

I'm not 100% sure about Tracker.autorun.

6
John Smith On

Explicitly specifying is indeed saving memory, sends less data over the wire and might give you a small performance boost. Another important use for it is as a security measure. Imagine that you want your client-side to subscribe to the Users collection, but you don't want the user's password or any other field containing sensitive information to be visible on the client. In that case, when you're publishing the collection, you'd do it this way:

Meteor.publish('secureUsers', function() {
  if(!this.userId) return null;
  return Meteor.users.find(this.userId, 
    {fields: 
      {
        someNonSensitiveField: 1, /* avatar information, for example */
        otherNonSensitiveField: 1
      }
    }
  );
});

This way only the specified fields will be included in the collection objects, leaving out the other data, which might be sensitive. Another approach is to specify which fields are sensitive and exclude them explicitly.

HTH!