mongodb 错误:无法初始化客户端|mongo-connect express-session

s1ag04yj  于 2023-04-05  发布在  Go
关注(0)|答案(7)|浏览(213)

我在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”)(session)
但错误显示..

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
不知道我错过了什么。
请帮帮我。
先谢了。
伊凡

rvpgvaaj

rvpgvaaj1#

所以看起来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,看看是否有帮助。
您可以阅读更多关于connect-mongo in their docs的信息。

anhgbhbe

anhgbhbe2#

以下是为我工作。

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
 }));
aemubtdh

aemubtdh3#

我所做的是从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)"
wydwbb8l

wydwbb8l4#

此为最新解决方案

  • 添加此行 *
    第一次
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'}),
        
      }));
46qrfjad

46qrfjad5#

还有另一个npm包connect-mongodb-session,https://www.npmjs.com/package/connect-mongodb-session安装它,它应该可以工作。
const MongoDBStore = require('connect-mongodb-session')(session);

tuwxkamq

tuwxkamq6#

这对我很有效

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

const dbUrl = process.env.DB_URL;

app.use(session({
    secret: 'thisismysecret',
    resave: false,
    saveUninitialized: false,
    store: MongoStore.create( {
        mongoUrl: dbUrl,
        touchAfter: 24 * 3600 
     }) }));
px9o7tmv

px9o7tmv7#

我有点晚了,但我正在努力解决这个确切的问题,我设法找到了一种方法来重用现有的数据库连接,而不是像其他人回答的那样通过将我们的db URI放在mongoUrl属性中来创建新的数据库连接,所以这里是我的解决方案,供任何未来的读者使用:
基本上,如果我们想在项目的其他地方重用数据库连接,MongoStore需要一个'client'或'clientPromise'。
现在,Mongo客户端在我们连接到数据库之前是不可用的(据我所知,客户端只是对打开的连接的引用)-当我们第一次启动服务器时,连接需要一点时间。
因此,我们需要手动创建一个Promise给MongoStore的'clientPromise'属性,它将在最终建立连接时解析到客户端。
为此,我们可以在mongoose.connection中添加一个事件监听器,这样当连接建立时,我们就可以在mongoose.connection上调用getClient()来获取客户端,然后用它解析Promise。

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

const mongoClientPromise = new Promise((resolve) => {
    mongoose.connection.on("connected", () => {
        const client = mongoose.connection.getClient();
        resolve(client);
    });
});

const sessionStore = MongoStore.create({
    clientPromise: mongoClientPromise,
    dbName: "myDb",
    collection: "sessions"
});

app.use(session({
    secret: mySecret,
    store: sessionStore
});

相关问题