MongoStore:无法初始化客户端,不接受mongoose连接对象

z5btuh9x  于 2022-11-13  发布在  Go
关注(0)|答案(2)|浏览(299)

我正在尝试使用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
    }
}))

......以及应用程序的其余部分。
为了能够将mongoose连接对象用作会话存储,我需要更改什么?
我已经在其他地方看过了,但是像这样的问题表明我们应该能够发送实际的mongoose连接,而不是重新发送连接字符串并在连接上加倍:Error: Cannot init client | mongo-connect express-session

sczxawaw

sczxawaw1#

下面是我如何使用此方法设置我的:https://github.com/jdesboeufs/connect-mongo/blob/092066300746f3733c0c3dac8cc378407ef5a26c/example/mongoose.js
如果您使用的是Compass,则最后完成此操作的关键是将“localhost”更改为“127.0.0.1

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

const app = express()
const port = 3000

const dbString = 'mongodb://127.0.0.1:27017';
const dbOptions = { 
    useNewUrlParser: true,
    useUnifiedTopology: true
}

const conn = mongoose.connect(dbString, dbOptions).then(m => m.connection.getClient());

app.use(express.json());
app.use(express.urlencoded({extended: true}));

const sessionStore = MongoStore.create({
    clientPromise: conn,
    dbName: "session"

})

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

app.get('/', (req, res, next) => {
    res.send('<h1>Hello Bret (sessions)</h1>')
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})
j5fpnvbx

j5fpnvbx2#

根据以下文档,MongoStore构造函数的mongooseConnection参数已更改为“client”: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

相关问题