Class constructor MongoStore cannot be invoked without 'new' (Express-NodeJs)Backend

Viewed 4362

I m creating react-auth . Firstly I created server side. I need to connect mongodb but i didnt manage.

const session = require('express-session') const Mongostore = require('connect-mongo')(session) ``const cors = require('cors')

app.use(session({ secret: 'secret', store: new Mongostore({ mongooseConnection: mongoose.connection }), resave: true, saveUninitialized: true }))

5 Answers

For those who want to the latest version of connect-mongo, the new syntax involves removing the parameter session from the require call and not using new any more but a method .create.

Here is what the documentation recommends:

const session = require('express-session');
const MongoStore = require('connect-mongo');

app.use(session({
  secret: 'foo',
  store: MongoStore.create(options)
}));

Basic usage would be:

app.use(session({
  store: MongoStore.create({ mongoUrl: 'mongodb://localhost/test-app' })
}));
      const session=require("express-session");
  const MongoStore=require("connect-mongo");
//*****************
  app.use(session({
   secret:"secret",
   cookie:{maxAge:60000},
   resave:false,
   saveUninitialized:false,
   store:MongoStore.create({mongoUrl:process.env.MONGO_URI}),
  

Please make the following changes on your code, from:

const MongoStore = require('connect-mongo')(session);

Use, instead:

const MongoStore = require('connect-mongo')

And in the session object options use:

store: MongoStore.create({ mongoUrl: process.env.CONNECTIONSTRING })

process.env.CONNECTIONSTRING is the link provided by mongodb that you may store in the .env

I tried downgrading the mongo-connect version as suggested above but found it more reliable to keep it up to date with current version and using the new method create with different key name, following the documentation guidelines

enter image description here

I also had the same Error, What i did was to npm i connect-mongodb-session

const MongoStore = require('connect-mongodb-session)(session)

I then created a middleware by session

    app.use(
      session({
      secret: 'keyboard cat',
      resave: false,
      saveUninitialized: false,
      store: new MongoStore({ mongooseConnection: process.env.MONGO_URI }),
  })
);

Instead of coding my URI directly, i instead loaded it from the .env file with process.env.MONGO_URI

Related