I'm trying to understand when it's best to use each of the following. Here is my rudimentary understanding:
app.locals -- good for storing global variables at the app level. all users/sessions will see the same values for these variables. the variables are available to all views.
res.locals -- good for storing variables for the specific request/response cycle. the variables are only available to the view associated with the response.
req.session -- good for storing variables associated with the unique user session (e.g., user name). these variables should be available to all views for the unique user/session.
The specific use case I have is as follows: A user runs query which retrieves data from mongodb. I now want the result of this query, which is a JSON array, available as a variable to ALL of the views (HTTP requests). What's the best way to "store" the result array so that each view can access it?
I now want the result of this query, which is a json array, available as a variables to ALL of the views. What's the best way to "store" the result array so that each view can access it?
When you say "available to ALL of the views" I assume you mean across all HTTP requests. If that is the case then you need to be aware that HTTP is a stateless protocol and does not provide for this. You'll need to develop your own mechanism for this.
One way of doing this is by cacheing this information (the array) on the server and retrieve it on every request (for example, retrieve it from memory rather than from MongoDB). You'll store a session ID on the cookie and based on this ID fetch it from cache when another requests comes through. There are several cache tools available (e.g. redis, memcached, et cetera) that you can chose to store the information in memory.
You could also cookie this information (the array itself) in which case it will be send back and forth between the client and the server on every HTTP request and very likely won't be a very good idea unless the data is very small.