0

我正在尝试使用 AWS DocumentDB(AWS 品牌的 MongoDB)来帮助我存储会话数据。我已经通过 mongoose 成功连接到我的 db.js 文件中的数据库。

当我尝试将此 mongoose 连接作为 MongoStore 构造函数中的 mongooseConnection 参数传递给时,我收到以下错误:

Assertion failed: You must provide either mongoUrl|clientPromise|client in options
xxxx/node_modules/connect-mongo/build/main/lib/MongoStore.js:119
            throw new Error('Cannot init client. Please provide correct options');
                  ^

Error: Cannot init client. Please provide correct options

我的 db.js 看起来像这样:

import * as fs from 'fs';
import mongoose from 'mongoose';

var ca = [fs.readFileSync("./certs/rds-combined-ca-bundle.pem")];  // AWS-provided cert

var connectionOptions = {
    useUnifiedTopology: true,
    useNewUrlParser: true,
    ssl: true,
    sslValidate: true,
    checkServerIdentity: false,
    sslCA: ca,
    replicaSet: 'rs0',
    readPreference: 'secondaryPreferred',
    retryWrites: false
};

var connectionString = 'mongodb://' + user + ':' + pwd + '@' + dbServerLocation + '/' + dbName;  // variables defined elsewhere and removed from this post.

mongoose.connect(connectionString, connectionOptions)
    .catch((err) => console.log(err));
}

export default mongoose.connection;

我的 server.js (main) 抛出错误如下所示:

import db from './db/db.js';
import session from 'express-session';
import MongoStore from 'connect-mongo';

db.on('error', () => console.error('MongoDB connection error.'));
db.on('reconnectFailed', () => console.error("Reconnection attempts to DB failed."));
db.on('connected', () => { console.log('Connected to DocumentDB database in AWS') });

import express from 'express';

const sessionStore = new MongoStore({
    mongooseConnection: db,
    collection: 'sessions'
})

var app = express();
app.use(session({
    resave: false,
    secret: 'secret word',
    saveUninitialized: true,
    store: sessionStore,
    cookie: {
        maxAge: 1000 * 60 * 60 * 24
    }
}))

...以及应用程序的其余部分。

为了能够将我的猫鼬连接对象用作会话存储,我需要进行哪些更改?

我在别处看过,但像这样的问题表明我们应该能够发送实际的猫鼬连接,而不是重新发送连接字符串并加倍连接: 错误:无法初始化客户端 | mongo-connect 快速会话

4

1 回答 1

1

原来 MongoStore 构造函数的 mongooseConnection 参数已根据此处的文档更改为“客户端”:https ://www.npmjs.com/package/connect-mongo

(我仍然收到错误 - 特别是现在我得到一个 'con.db' 不是 MongoStore 的函数......但由于它与 OP 相关,答案是更改为 'client' 而不是 'mongooseConnection'。 )

对于那些追随我的人 - 特别是那些认为他们有 mongo 连接并希望将其作为client参数传递的人......你需要调用该getClient()函数来帮助实现这一点 - 就像这样:

const sessionStore = new MongoStore({
    client: dbConnection.getClient(),
    collectionName: 'sessions'
})

在此处的 connect-mongo 迁移 wiki 中找到此内容:https ://github.com/jdesboeufs/connect-mongo/blob/HEAD/MIGRATION_V4.md

于 2021-05-18T17:42:51.950 回答