v1.8.0Published 5 years ago

This package has not had recent updates. Please investigate it's current state before committing to using it in your project.

userCache for Meteor

userCache builds upon three simple premises:

  1. Every time you run Meteor.user() on the server, it has to call the database to retrieve the user document
  2. Every time a user account connects to your server, Meteor automatically subscribes for to their user document
  3. Whenever a subscription is running, the documents that are part of that subscription are cached to the server

Thus, instead of querying the database every time that Meteor.user() is ran, we could first see if it's sufficient to retrieve it from the server-side cache (also known as MergeBox). Since MergeBox is fast and real-time (in fact, it gets the data before the client), the risk of stale data may be insignificant.

The benefit of using userCache are:

  • fewer database queries and the associated overhead
  • faster performance and response time
  • complete backwards compatibility

Now with support for Meteor 1.8

How to Use

To add the package, run:

meteor add msavin:usercache

Once you add the package, Meteor.user() will be enhanced with new properties.

1Meteor.user()                              // works as usual
2Meteor.user(true)                          // gets data from mergebox
3Meteor.user("")	 	   // verifies if the fields are in MergeBox. If not, it retrieves the document from the database
4Meteor.user(['', 'email'])     // verifies if the fields are in MergeBox. If not, it retrieves the document from the database

Meteor.user() will continue to return the user document as usual. If can satisfy your field requirements, it will do so from MergeBox. If it cannot, it will retrieve the data from the database as usual.


In the example below, we are using Meteor.user() for a roles check to ensure that the user is not banned. Typically, this would require us to ping the database. However, with the userCache package, we can bypass that entire query, and all the processing that comes with it. By doing so, we improve performance and speed up response time.

2	"posts/create": function (content) {
3		var userDoc = Meteor.user(["profile.roles"])
5		var authorization = function () {
6			return !!userDoc.profile.roles.includes("banned");
7		}
9		if (authorization()) {
10			Posts.insert({
11				user: Meteor.userId(),
12				date: new Date(),
13				content: content
14			})
15		}
16	}