如何在NodeJS中存储MongoDB中的会话?

时间:2013-12-03 21:04:50

标签: node.js mongodb session express

我使用connect-mongo模块在​​express中存储来自mongodb的会话。像这样使用它:

app.use(express.session({
    'secret': config.APP_SECRET,
    'store': new MongoStore({
        'db': db
    })
}));

其中:

var MongoStore = require(config.MODULES_DIR + 'connect-mongo')(express);
var db = mongoose.connection; // already connected as i use in in callback

但是当使用会话时我会收到此错误:

TypeError: Object #<Object> has no method 'open'
    at MongoStore._open_database (/node_modules/connect-mongo/lib/connect-mongo.js:174:15)
    at MongoStore._get_collection (/node_modules/connect-mongo/lib/connect-mongo.js:169:14)
    at MongoStore.get (/node_modules/connect-mongo/lib/connect-mongo.js:211:10)
    at Object.session [as handle] (/node_modules/express/node_modules/connect/lib/middleware/session.js:314:11)
    at next (/node_modules/express/node_modules/connect/lib/proto.js:193:15)
    at Object.cookieParser [as handle] (/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js:60:5)
    at next (/node_modules/express/node_modules/connect/lib/proto.js:193:15)
    at Object.urlencoded [as handle] (/node_modules/express/node_modules/connect/lib/middleware/urlencoded.js:49:37)
    at next (/node_modules/express/node_modules/connect/lib/proto.js:193:15)
    at Object.json [as handle] (/node_modules/express/node_modules/connect/lib/middleware/json.js:51:37)

2 个答案:

答案 0 :(得分:3)

如果您想使用Mongoose连接,则需要使用恰当命名的mongoose_connection选项:

new MongoStore({
  mongoose_connection : db 
})

答案 1 :(得分:2)

我总是发现使用MongoUri连接更容易。大多数数据库服务都会为您提供一个数据库服务。看起来应该是这样的:

var mongoUri = 'mongodb://username:password@foo.mongohq.com/port/db'

app.use(express.session({
    store   : new MongoStore({
        url  : mongoUri
    })
}))