Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting information from node.js session vs getting it from database

I am using "express-session" with a MongoStore from "connect-mongo". Now from my understanding, the session is somehow stored in mongodb. Lets say that I have stored the username in session.

Now, lets say I frequently need the favorite color of the user. I have two way of doing it. Store the favorite color in session, or use the username from session to query the DB.

Now my question is, since sessions are stored in db, querying from session will eventually query the db. So, what's the difference between the two methods. If they are different, which one is better?

like image 590
forthright48 Avatar asked Feb 20 '26 08:02

forthright48


1 Answers

Retrieving the session data requires a database query. If you would store the favorite color in the session, getting that preference would require that one query.

If you don't store the color in the session, you would need two database queries: one for the session, one for the user data that holds the color preference.

So if you know that during a session you will be needing the color information a lot, it would be better to copy that information into the session (although don't expect massive performance improvements, MongoDB and your OS will try and keep often-used database records in memory as much as possible).

A possible downside would be that in case of changes to preferences you need to update multiple documents (if the user changes their favorite color, you need to update both the session document and the user document in the database).

like image 80
robertklep Avatar answered Feb 22 '26 02:02

robertklep