Error: Cannot init client | mongo-connect express-session

Error: Cannot init client | mongo-connect express-session

我在 mongodb 上尝试保存会话时遇到错误。这是我的代码..

const express = require("express");
const session = require("express-session");
const MongoStore = require("connect-mongo").default;
const app = express();

let sessionOptions = session({
  secret: "JavaScript is cool",
  store: MongoStore.create({ client: require("./db") }),
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: 1000 * 60 * 60 * 24, httpOnly: true },
});

app.use(sessionOptions);
const router = require("./router");
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(express.static("public"));
app.set("views", "views");
app.set("view engine", "ejs");

app.use("/", router);

module.exports = app;

和db.js

const dotenv = require("dotenv");
dotenv.config();
const mongodb = require("mongodb");

mongodb.connect(
  process.env.CONNECTIONSTRING,
  { useNewUrlParser: true, useUnifiedTopology: true },
  (err, client) => {
    module.exports = client;
    const app = require("./app");
    app.listen(process.env.PORT);
  }
);

错误就在这里..

Assertion failed: You must provide either mongoUr|clientPromise in options
/home/irfan/Desktop/Brad_Sciff/Complex_App/node_modules/connect-mongo/build/main/lib/MongoStore.js:121
            throw new Error('Cannot init client');
            ^

    Error: Cannot init client
        at new MongoStore (/home/irfan/Desktop/Brad_Sciff/Complex_App/node_modules/connect-mongo/build/main/lib/MongoStore.js:121:19)
        at Function.create (/home/irfan/Desktop/Brad_Sciff/Complex_App/node_modules/connect-mongo/build/main/lib/MongoStore.js:137:16)
        at Object.<anonymous> (/home/irfan/Desktop/Brad_Sciff/Complex_App/app.js:9:21)
        at Module._compile (internal/modules/cjs/loader.js:778:30)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
        at Module.load (internal/modules/cjs/loader.js:653:32)
        at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
        at Function.Module._load (internal/modules/cjs/loader.js:585:3)
        at Module.require (internal/modules/cjs/loader.js:692:17)
        at require (internal/modules/cjs/helpers.js:25:18)

我尝试将 const MongoStore = require("connect-mongo").default 更改为 const MongoStore = require("connect -mongo")(会话)

但是显示错误..

const MongoStore = require("connect-mongo")(session);
                                           ^

TypeError: require(...) is not a function
    at Object.<anonymous> (/home/irfan/Desktop/Brad_Sciff/Complex_App/app.js:4:44)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at mongodb.connect (/home/irfan/Desktop/Brad_Sciff/Complex_App/db.js:10:17)
    at /home/irfan/Desktop/Brad_Sciff/Complex_App/node_modules/mongodb/lib/utils.js:693:5

使用 Connect-mongo 4.2,express-session 1.17.1 express 4.17.1 mongodb 3.6.4

不知道我错过了什么。

请帮忙。

提前致谢。

伊尔凡.

看来 connect-mongo 最近更新了。我今天也遇到了这个问题,这是我解决它的方法。

过去的样子:

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

app.use(
  session({
    ...options
    store: new MongoStore({ mongooseConnection: mongoose.connection  }),
  })
);

现在怎么样:

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

app.use(
  session({
    store: MongoStore.create({ mongoUrl: process.env.MONGO_URI }),
    ...options
  })
);

尝试将连接字符串传递给 mongoURL 而不是 client,看看是否有帮助。

您可以阅读有关连接的更多信息-mongo in their docs

这是最新的解决方案

添加这行

第一

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

第二

app.use(session(
      {
        secret: '**something** like mysupersecret',
        store: MongoStore.create({ 
          mongoUrl: '**your url**like mongodb://localhost/test-app'}),
        
      }));

以下是我的作品。

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

const url = 'mongodb://localhost/mydb';
mongoose.connect(url, { useNewUrlParser: true, useCreateIndex: true, 
useUnifiedTopology: true, useFindAndModify: true });
const connection = mongoose.connection;

connection.once('open', () => {
    console.log("database connected successfully...");
}).catch(err => {
    console.log("connection failed...");
});

// session store

let store = new MongoStore({
   mongoUrl: url,
   collection: "sessions"
});

 // session config

 app.use(session({
   secret: process.env.COOKIE_SECRET,
   resave: false,
   store: store,
   saveUninitialized: false,
   cookie: { maxAge: 1000 * 60 * 60 * 24 }, // 24 hours
 }));

还有一个 npm 包 connect-mongodb-session, https://www.npmjs.com/package/connect-mongodb-session 安装它,它应该可以工作。

const MongoDBStore = require('connect-mongodb-session')(session);

我所做的是从 mongodb 版本 4 降级到版本 3。因此,在您的终端中,卸载 connect-mongo 并重新安装较低版本。

"npm uninstall connect-mongo"

"npm i connect-mongo@3"

这使您能够将会话传递给 MongoStore。

"const path = require('path')

const express = require('express') 

const mongoose  = require ('mongoose')

const dotenv = require('dotenv')

const morgan = require('morgan')

const exphbs = require ('express-handlebars')

const passport = require('passport')

const session = require ('express-session')

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