简体   繁体   中英

Why this error is occuring and how i can solve the problem?

My code is:

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

mongoose.connect(dbUrl, {
    useNewUrlParser: true,

    useUnifiedTopology: true

});
const store = new MongoDBStore({
    url: dbUrl,
    secret: 'thisshouldbeabettersecret!',
    touchAfter: 24 * 60 * 60
})
const sessionConfig = {
    store,
    name: 'session',
    secret: 'thisshouldbeabettersecret!',
    resave: false,
    saveUninitialized: true,
    cookie: {
        httpOnly: true,
        // secure: true,
        expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
        maxAge: 1000 * 60 * 60 * 24 * 7
    }
}

app.use(session(sessionConfig));

Error is:

const MongoDBStore = require("connect-mongo")(session)
                                             ^

TypeError: Class constructor MongoStore cannot be invoked without 'new'
    at Object.<anonymous> (C:\Users\aach0\Desktop\Web dev files\Yelp Camp\app.js:23:46)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

Welcome!

I think you're approaching this from the wrong angle. Have you taken a look at the documentation for connect-mongo ? ( https://www.npmjs.com/package/connect-mongo )

Here they are passing in the mongodb store as the store option to the session, whereas you're trying to pass in the session to the mongodb store.

This is the example they provide in the docs:

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

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

Finally as a tip from now onwards, try to make the title of your question a bit more descriptive, and for any other questions please attach what you have tried and with what results as this will help other people answer your question.

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