使用express框架時,用MongoDB存放session時,出現錯誤,解決方法

使用express框架時,用MongoDB存放session時,出現錯誤以下:node



D:\WorkSpace\nodejs\user\node_modules\connect-mongo\lib\connect-mongo.js:153
          throw new Error('Error connecting to database');
                ^
Error: Error connecting to database
    at D:\WorkSpace\nodejs\user\node_modules\connect-mongo\lib\connect-mongo.js:153:17
    at D:\WorkSpace\nodejs\user\node_modules\connect-mongo\node_modules\mongodb\lib\mongodb\db.js:229:16
    at null.<anonymous> (D:\WorkSpace\nodejs\user\node_modules\connect-mongo\node_modules\mongodb\lib\mongodb\connection\server.js:578:7)
    at EventEmitter.emit (events.js:106:17)
    at null.<anonymous> (D:\WorkSpace\nodejs\user\node_modules\connect-mongo\node_modules\mongodb\lib\mongodb\connection\connection_pool.js:139:15)
    at EventEmitter.emit (events.js:98:17)
    at Socket.<anonymous> (D:\WorkSpace\nodejs\user\node_modules\connect-mongo\node_modules\mongodb\lib\mongodb\connection\connection.js:475:10)
    at Socket.EventEmitter.emit (events.js:95:17)
    at net.js:441:14
    at process._tickCallback (node.js:415:13)
web

解決方法以下:mongodb

(數據庫不帶用戶和密碼的方法)數據庫

將  store: new MongoStore({db:settings.db})express

替換成     store: new MongoStore({host:settings.host, port:settings.port, db:settings.db)})
cookie

在開始加上  format = require('util').formatsession

app.use(express.session({
    secret: settings.cookieSecret,
    key: settings.db,
    cookie: {maxAge: 1000 * 60 * 30},//30 minute
    store: new MongoStore({host:settings.host, port:settings.port, db:settings.db)})
    /*store: new MongoStore({db:settings.db})*/
}));app


(數據庫帶用戶和密碼的方法)
框架

將  store: new MongoStore({db:settings.db})ui

替換成     store: new MongoStore({url:format("mongodb://%s:%s@%s:%s/%s",settings.uid, settings.pwd, settings.host, settings.port, settings.db)})

在開始加上  format = require('util').format

app.use(express.session({    secret: settings.cookieSecret,    key: settings.db,    cookie: {maxAge: 1000 * 60 * 30},//30 minute    store: new MongoStore({url:format("mongodb://%s:%s@%s:%s/%s",settings.uid, settings.pwd, settings.host, settings.port, settings.db)})    /*store: new MongoStore({db:settings.db})*/}));

相關文章
相關標籤/搜索