在MongoClient.connect中初始化会话

时间:2014-07-30 17:00:16

标签: node.js mongodb express

我正在尝试重用数据库对象。会话初始化在Mongoconnect回调之外正常工作。但是当我在回调中移动它时,会话cookie没有在浏览器中设置。任何想法??

var express=require('express');
var bodyParser=require('body-parser');
var cookieParser=require('cookie-parser');
var session=require('express-session');

var mongodb=require('mongodb'),
MongoClient = mongodb.MongoClient;
var MongoStore = require('connect-mongo')(session);

var util=require('util');
var assert=require('assert');
var db;



var app=express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(cookieParser());


MongoClient.connect('mongodb://localhost:27017/mydb',function(err,database){
    if(!err)
    {


        app.use(session(
            { name:'sessionCookie',secret:'secret',saveUninitialized:true,resave:true ,
            store: new MongoStore({  db:database })
            }
            ));

        app.listen(3000);

    }

});  

1 个答案:

答案 0 :(得分:1)

这似乎是app对象初始化和会话被激活之间的时间问题。我稍微修改了代码,问题似乎已得到解决。我不完全确定根本原因。随意填写

var express=require('express');
var bodyParser=require('body-parser');
var cookieParser=require('cookie-parser');
var session=require('express-session');

var mongodb=require('mongodb'),
MongoClient = mongodb.MongoClient;
var MongoStore = require('connect-mongo')(session);

var util=require('util');
var assert=require('assert');
var db;



var app;



MongoClient.connect('mongodb://localhost:27017/mydb',function(err,database){
    if(!err)
    {
app=express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(cookieParser());
        app.use(session(
            { name:'sessionCookie',secret:'secret',saveUninitialized:true,resave:true ,
            store: new MongoStore({  db:database })
            }
            ));

        app.listen(3000);
    }

});