NodeJS使用Mongo进行Mongoose connect-mongo会话存储

时间:2014-10-17 05:13:31

标签: node.js express connect-mongo

我尝试以我可以在使用mongo持久化的nodejs中使用会话的方式配置我的connect-mongo。我使用以下代码

var mongoose = require('mongoose');

function connect(url, callback) {
  mongoose.connect(url);

  var connection = mongoose.connection;
  connection.on('error', console.error.bind(console, 'connection error:'));
  connection.once('open', function() {
      console.log("Mongoose connected at: ", url);
      callback(connection);
  });
}

var express = require("express");
var body_parser = require('body-parser');
var cookie_parser = require('cookie-parser');
var hogan_express = require('hogan-express');
var session = require('express-session');
var mongo_store = require('connect-mongo')(session);

var express = require("express");

var app = express();

app.engine('html', hogan_express);

app.set('view engine', 'html');
app.set("views", "views");

app.use("/libs", express.static("bower_components"));

if (!config.development) {
    app.use(express.static("min"));
}
app.use(express.static("public"));

connect("MONGODBURL",function(mongoose_connection){
    app.use(body_parser.json());
    app.use(cookie_parser());
    app.use(session({
        secret: "asd",
        store: new mongo_store({
            mongoose_connection: mongoose_connection
            // db: mongoose_connection.db
        })
    }));

})

我已经尝试了所有的东西,但是执行了一些代码,我从来没有参与过对象会话。

获取:TypeError:无法设置未定义的属性'asd'

代码:

app.get("/rest/test",function(req, res) {
    req.session.asd="test";
    res.send(req.session.asd)
});

Somone可以给出解决方案的暗示吗?

1 个答案:

答案 0 :(得分:1)

您需要在 配置会话后定义路线

...
app.use(session....
...
app.get("/...

在你的情况下你的连接回调内部。也可能只是开始在里面听。

connect("MONGODBURL",function(mongoose_connection){
    app.use(body_parser.json());
    app.use(cookie_parser());
    app.use(session({
        secret: "asd",
        store: new mongo_store({
            mongoose_connection: mongoose_connection
            // db: mongoose_connection.db
        })
    }));
    app.get("/rest/test",function(req, res) {
        req.session.asd="test";
        res.send(req.session.asd)
    });
    app.listen(...
});