如何使用Express和MongoStore从MongoDB集合中查找会话

时间:2022-05-06 16:48:01

I am implementing a session store using Node/Express/Mongo. My problem is that I cannot retrieve any sessions from my sessions collection, so I am unable to determine whether a user has already logged in.

我正在使用Node / Express / Mongo实现会话存储。我的问题是我无法从会话集合中检索任何会话,因此我无法确定用户是否已登录。

I am using MongoSkin, MongoStore, and mongo-connect, although I don't mind using Mongoose and other tools.

我使用MongoSkin,MongoStore和mongo-connect,虽然我不介意使用Mongoose和其他工具。

Here is my debug output:

这是我的调试输出:

// Check whether the current user has a session.
// If so, adds "currentUser" to the request.
// Else, redirect to the login page.
function loadUser(req, res, next) {
    console.log("loadUser: checking loadUser...");
    var db = req.db;
    console.log("current req.session.token:");
    console.log(req.session.token);
    console.log("current req.session:");
    console.log(req.session);
    if (req.session.token) {
        // Look up the session id in the database 'sessions' collection.
        db.collection('sessions').findOne({token : req.session.token}, function(err, user) {
            console.log("found user by looking up token:");
            console.log(user);
            if (user) {
                req.currentUser = user;
                next();
            } else {
                console.log("token not in 'sessions', redirecting...");
                res.redirect('/login/webapp_login.html');
            }
        });
    } else {
        console.log("no token, redirecting...");
        res.redirect('/login/webapp_login.html');
    }
}

And here is the console output:

这是控制台输出:

loadUser: checking loadUser...
current req.session._id:
53acb8e1b7b297dc29681def
current req.session:
{ cookie: 
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true },
  isLogged: 21,
  username: 'sessiontest1',
  token: '57a6dfe0bea9150bd4e2d1f76974e88b',
}
found user by looking up token:
null
token not in 'sessions', redirecting...

Along with:

        db.collection('sessions').find(req.session._id, function(user) {

I also tried:

我也尝试过:

db.collection('sessions').findOne({session:{token:req.session.token}}, function(err, user) {

but I still get null and the function redirects. Am I missing something? Any suggestions would be helpful. I am using MongoSkin, although I am open to solutions in Mongoose as well.

但我仍然得到null并且函数重定向。我错过了什么吗?任何的意见都将会有帮助。我使用MongoSkin,虽然我也对Mongoose的解决方案持开放态度。

Additionally, I know that my database is configured correctly because I checked the command line:

另外,我知道我的数据库配置正确,因为我检查了命令行:

> db.sessions.find().pretty()
{
        "_id" : "vnftBGNFVQ3S4lHiIB_omOxWDu01kFuH",
        "session" : "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":t
rue,\"path\":\"/\"},\"isLogged\":6}",
        "expires" : ISODate("2014-07-09T03:44:54.863Z")
}
{
        "_id" : "-AMKc_kIzOOAn_eQJ6RJpvTgWoargLaJ",
        "session" : "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":t
rue,\"path\":\"/\"},\"isLogged\":20,\"username\":\"sessiontest1\",\"token\":\"57a6dfe0bea
9150bd4e2d1f76974e88b\"}",
        "expires" : ISODate("2014-07-11T06:35:14.835Z")
}

What is going wrong, and why can't I retrieve a session from my sessions collection?

出了什么问题,为什么我不能从会话集合中检索会话?

Update running

db.collection('sessions').find({"session" : /./}, function(err, user) {

db.collection('sessions')。find({“session”:/。/},function(err,user){

gives me an output, so I believe the problem is matching a record with a field within the session field's string. The session field, shown in the database output above, is problematic because it one long string and not a nested JSON.

给我一个输出,所以我认为问题是将记录与会话字段的字符串中的字段匹配。上面的数据库输出中显示的会话字段是有问题的,因为它是一个长字符串而不是嵌套的JSON。

Also, my sessions records are inserted automatically after adding this to my app.js:

此外,我的会话记录在将其添加到我的app.js后会自动插入:

app.use(expressSession({
    secret: 's3cretc0de',      
    store: new MongoStore({
        url: mongoUrl      
    }, function () {
        console.log("db session connection open");
    })
}));

And I added the token and username fields within my router, shown below:

我在路由器中添加了令牌和用户名字段,如下所示:

router.get('/verify', function(req, res) {
    req.session.username = username;
    req.session.token = req.query.token;
}

Am I missing something? Any help would be greatly appreciated.

我错过了什么吗?任何帮助将不胜感激。

1 个解决方案

#1


4  

When you use MongoStore for storing your session data you don't need to query the MongoDB directly. The module does everything for you.

当您使用MongoStore存储会话数据时,您不需要直接查询MongoDB。该模块为您完成所有事情。

You can just use req.session to get your session data.

您可以使用req.session获取会话数据。

So in your routes you can do something like:

因此,在您的路线中,您可以执行以下操作:

app.get('/', function(req, res){
  // check if the username is set in the session
  if (!req.session.username) {
    // redirect it to login page
    res.redirect('/login');
  } else {
    // do something
  }
});

app.post('/login', function(req, res) {
    // you would check check the username & password here
    // if (username == '...' /&& password ...)

    // set the username in the session session 
    req.session.username = username; 
});

#1


4  

When you use MongoStore for storing your session data you don't need to query the MongoDB directly. The module does everything for you.

当您使用MongoStore存储会话数据时,您不需要直接查询MongoDB。该模块为您完成所有事情。

You can just use req.session to get your session data.

您可以使用req.session获取会话数据。

So in your routes you can do something like:

因此,在您的路线中,您可以执行以下操作:

app.get('/', function(req, res){
  // check if the username is set in the session
  if (!req.session.username) {
    // redirect it to login page
    res.redirect('/login');
  } else {
    // do something
  }
});

app.post('/login', function(req, res) {
    // you would check check the username & password here
    // if (username == '...' /&& password ...)

    // set the username in the session session 
    req.session.username = username; 
});