jdesboeufs / connect-mongo

MongoDB session store for Express
MIT License
1.96k stars 343 forks source link

Error: Unable to find the session to touch #407

Closed Abourass closed 3 years ago

Abourass commented 3 years ago

databaseConnect


type databaseURI = { dbURI: string; }

/**
 * @summary Connects to Atlas, returns the connection;
 * @param dbURI - {dbURI: `${process.env.mongoURI}`}
 * @param connectionString - The string you want logged upon connection
 * @category Middleware
 * @internal
 */
export = async({dbURI}: databaseURI, connectionString: string) => {
  const config: ConnectionOptions = {keepAlive: true, useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true};
  const connect = async(URI: string): Promise<Mongoose> => {
    try {
      return mongoose.connect(URI, config);
    } catch (err) {
      console.error(`Error connecting to database: ${err}`);
    }
  };

  const atlas = await connect(dbURI);
  console.log(chalk.keyword(chooseColor()).inverse(connectionString));
  atlas.connection.on('disconnected', connect);
  atlas.connection.on('error', console.error);

  return atlas.connection;
}

And then I initialize in my app.ts

// ==> Initialize our connection to Atlas <==
const nativeClient = () => databaseConnect(
  {dbURI: `${process.env.mongoURI}`},
  ' Atlas has shouldered the burden | Database Aloft 🚀 ',
).then(db => db.getClient());

// ...yadda yadda yadda

// ==> Create Session Object for Use <==
app.use(session({
  secret: 'yaddaYadda',
  name: 'yaddaYadda',
  resave: false,
  saveUninitialized: false,
  store: MongoStore.create({
    clientPromise: nativeClient(),
  }), // ==> Session store <==
  cookie: {path: '/', httpOnly: true, secure: 'auto', maxAge: 60000 * 60 * 24},
}));
braitsch commented 3 years ago

I'm getting this error as well when attempting to backup or restore a db. It seems like res.send is triggering the touch method as described here which throws an error if req.session hasn't been modified.

app.get('/admin/restore', function(req, res)
{
    var dir = path.join(__dirname, 'database');
    exec('mongorestore --drop '+dir, function(e, stdout, stderr) {
        log('* restoring database:', app.get('db_name'));
        if (e) {
            log(stderr);
            res.status(500).send(e);
        }   else{
            console.log('database successfully restored');
        // modifying req.session w/ a random value avoids throwing an error but this shouldn't be required //
            req.session.randomVal = Math.round(Math.random()*9999);
            res.sendStatus(200);
        }
    });
});
mingchuno commented 3 years ago

Link: #390

mingchuno commented 3 years ago

Wait, did you guys update to the latest version? It fixed the issue. @braitsch @Abourass