简体   繁体   中英

Regarding efficiency of passport.js module “deserializeUser” in node.js

So I was looking into the document regarding passport.js module serialize users to keep logged in users in session. (A little above the Username & Password parts). I'm using mongodb, with mongoose

passport.deserializeUser(function(id, done) {
  console.log("this code is used again! ");
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

I test these code in example they gave. So it looks that this piece of code is executed every time when the logged-in user refresh a page.

Say there are 100,000 users and there are 10 pages in this entire application, it means there will be 1 million look-ups, just to maintain in session status for every one. Doesn't this sounds too inefficient? Does most application do this kind database search?

Or am I making mistaking understand it?

There's nothing stopping you from using a cache or similar approach. One of them could be https://www.npmjs.com/package/cache-manager but do shop for more!

Alternatively, if you don't really need to know all the user information all the time you can serialize/deserialize the user id only and load the user record on demand. In your instance just pass through function:

passport.deserializeUser(function(id, done) {
   console.log("this code is used again! ");
   done(null, id);
});

If that's not enough you could deserialize to an object like this:

passport.deserializeUser(function(id, done) {
   console.log("this code is used again! ");
   done(null, {id: id, user: function(done){
       User.findById(id, function(err, user) {
         done(err, user);
       });
   }});
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM