使用express框架时,用MongoDB存放session时,出现错误如下:
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)解决方法如下:
(数据库不带用户和密码的方法)
将 store: new MongoStore({db:settings.db})
替换成 store: new MongoStore({host:settings.host, port:settings.port, db: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({host:settings.host, port:settings.port, db:settings.db)}) /*store: new MongoStore({db:settings.db})*/}));(数据库带用户和密码的方法)
将 store: new MongoStore({db:settings.db})
替换成 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})*/}));