Does fetching from a collection on the server always hit the database?

on the client, i understand fetch to pull from the local MiniMongo instance, making it cheap and scalable (with regard to server load). does Meteor keep any in-memory document cache on the server, or does every fetch incur a database hit?

i’m particularly curious about Meteor.user() - does this always perform a database hit?

i would assume that the connection keeps the current user’s id in process memory and that Meteor.userId() is super cheap, but if Meteor.user() is hitting the database every time that makes it fantastically more expensive.

this was a side thought while working on something else, so i haven’t really looked into it besides a few google searches that didn’t turn up much.

thanks.

You can’t use Meteor.userId() on server, only this.userId, which should be in-memory. AFAIK, there is no caching going on server and every fetch hits the database.

thanks.

with regards to Meteor.userId(), the docs say “Anywhere but publish functions”, and it seems to work fine on the server:

http://docs.meteor.com/api/accounts.html#Meteor-userId

1 Like

Ah ok. Always used this.userId and it seems that Meteor.userId() is not hitting the DB if you take a closer look at the inner workings.

userId() {
    var currentInvocation = DDP._CurrentInvocation.get();
    if (!currentInvocation)
       throw new Error("Meteor.userId can only be invoked in method calls. Use this.userId in publish functions.");
    return currentInvocation.userId;
}

my question was in relation to developing libs and helpers. it doesn’t make any sense to ask for the current user on the server unless you’re in the context of a method call, so it should fail outside of that.

my concern was about burying Meteor.user() inside functions where it might not be obvious from the outside, which it seems like a poor idea to do… if it’s a database hit, it should be apparent and explicit given the cost.