index.js:
..
var MongoStore = require( 'connect-mongo' )( session );
var db = require( path.join( __dirname, 'db.js' ) );
..
db.connect( conStr, function( err ) {
if( err ) {
console.log( 'Connect to mongoDb failed!' );
process.exit( 1 );
} else {
app.listen( port, function() {
console.log( 'App listening on port: ' + port );
});
}
});
...
app.use( session ({
name: 'bbn.sid',
secret:'shopusersessionsecret',
resave: false,
saveUninitialized: false,
store: new MongoStore( { db: db.get() } ),
cookie: {
maxAge: 180 * 60 * 1000,
}
}));
..
db.js:
...
var database = null;
function connect( url, done ) {
if( database ) return done();
MongoClient.connect( url, function( err, db ) {
if( err ) return done( err );
database = db;
done();
});
}
function get() {
return database;
}
...
如果我正在创建与会话商店的新连接(通过提供网址) 看起来没问题,但如果我试图使用现有的mongo连接,我会收到以下错误:
E:\Proj\bbn\node_modules\connect-mongo\src\index.js:105
throw new Error('Connection strategy not found');
^
Error: Connection strategy not found
at MongoStore (E:\Proj\bbn\node_modules\connect-mongo\src\index.js:105:23)
at Object.<anonymous> (E:\Proj\bbn\index.js:50:12)
at Module._compile (module.js:541:32)
看来,会话中间件正在调用而不是mongo db connection初始化?
答案 0 :(得分:0)
将所有app.use中间件放在connect callback中:
mongoclient.connect(mongourl, (error, database) => {
if (error) return console.log(error);`
db = database;
app.use...
app.use...
app.listen...
}