简体   繁体   English

node.js + express.js:使用mongodb / mongoose进行会话处理

[英]node.js + express.js: session handling with mongodb/mongoose

Right now i'm storing my session data in the "memory store" which comes bundled with connect(express). 现在我将会话数据存储在与connect(express)捆绑在一起的“内存存储”中。 But I want/have to change this for production. 但是我想/必须改变这个以进行生产。

The application is using mongodb and I installed mongoose to handle all db-communications. 该应用程序正在使用mongodb,我安装了mongoose来处理所有数据库通信。

eg Connect to the DB after initializing my app: 例如,在初始化我的应用程序后连接到数据库:

var mongo = require('mongoose');
mongo.connect('mongodb://localhost/myDb');
mongo.connection.on('open', function () {
  app.listen(3000);
}

I found the connect-mongodb module, but I don't know how to implement it using mongoose, or if it's actually possible? 我找到了connect-mongodb模块,但是我不知道如何使用mongoose实现它,或者它实际上是否可行? I need to add something like this: 我需要添加这样的东西:

var mongoStore = require('connect-mongodb');
// ...
app.use(express.session({
  secret: 'topsecret',
  maxAge: new Date(Date.now() + 3600000),
  store: new mongoStore({ db: 'myDb' })
}));

or do I have to define my db connection a second time using the mongodb-module directly? 或者我是否必须直接使用mongodb-module定义我的数据库连接?

in the end i'm using a bit of every answer that was given before: 最后我使用了之前给出的一些答案:

  • i switched from connect-mongodb to connect-mongo module 我从connect-mongodb切换到connect-mongo模块
  • i'm using a general conf object to store my configuration data 我正在使用常规conf对象来存储我的配置数据
  • there are two db connections because it's easier to handle for me (maybe changed later on, if/when a new version of mongoose/express comes out) 有两个数据库连接,因为它更容易为我处理(如果/当一个新版本的mongoose / express出来时,可能会在以后更改)

requirements: 要求:

var express = require('express'),
    MongoStore = require('connect-mongo')(express),
    mongo = require('mongoose');

conf object: conf对象:

var conf = {
  db: {
    db: 'myDb',
    host: '192.168.1.111',
    port: 6646,  // optional, default: 27017
    username: 'admin', // optional
    password: 'secret', // optional
    collection: 'mySessions' // optional, default: sessions
  },
  secret: '076ee61d63aa10a125ea872411e433b9'
};

then i can configure it like this: 然后我可以像这样配置它:

app.configure(function(){
  // ...
  app.use(express.cookieParser());
  app.use(express.session({
    secret: conf.secret,
    maxAge: new Date(Date.now() + 3600000),
    store: new MongoStore(conf.db)
  }));
  // important that this comes after session management
  app.use(app.router);
  // ...
});

and finally connect to mongodb a second time using mongoose: 最后使用mongoose第二次连接到mongodb:

var dbUrl = 'mongodb://';
dbUrl += conf.db.username + ':' + conf.db.password + '@';
dbUrl += conf.db.host + ':' + conf.db.port;
dbUrl += '/' + conf.db.db;
mongo.connect(dbUrl);
mongo.connection.on('open', function () {
  app.listen(3000);
});

Please include 请包括

app.use(express.cookieParser());

directly before 直接之前

app.use(express.session({

Otherwise throws error as below, 否则抛出错误如下,

TypeError: Cannot read property 'connect.sid' of undefined TypeError:无法读取未定义的属性“connect.sid”

It looks like you could do this to setup connect-mongodb assuming your mongoose connection code above is run earlier: 看起来您可以这样设置connect-mongodb假设您之前运行的mongoose连接代码:

app.use(express.session({
  secret: 'topsecret',
  maxAge: new Date(Date.now() + 3600000),
  store: new mongoStore({ db: mongoose.connections[0].db })
}));

For express 4x: 快递4x:

var express = require('express'),
    session = require('express-session'),
    MongoStore = require('connect-mongo')(session),
    mongo = require('mongoose');

var conf = {
  db: {
    db: 'myDb',
    host: '192.168.1.111',
    port: 6646,  // optional, default: 27017
    username: 'admin', // optional
    password: 'secret', // optional
    collection: 'mySessions' // optional, default: sessions
  },
  secret: '076ee61d63aa10a125ea872411e433b9'
};

app.configure(function(){
  app.use(express.cookieParser());
  app.use(session({
    secret: conf.secret,
    maxAge: new Date(Date.now() + 3600000),
    store: new MongoStore(conf.db)
  }));
});

var dbUrl = 'mongodb://';
dbUrl += conf.db.username + ':' + conf.db.password + '@';
dbUrl += conf.db.host + ':' + conf.db.port;
dbUrl += '/' + conf.db.db;
mongo.connect(dbUrl);
mongo.connection.on('open', function () {
  app.listen(3000);
});

session has been moved to it's own module, so you need to require it and use session when configuring the MongoStore . session已被移动到它自己的模块,因此您需要在配置MongoStorerequire它并使用session

So connect-mongodb does not use Mongoose, it uses the node-mongodb-native driver ( ie: npm install mongodb ). 所以connect-mongodb不使用Mongoose,它使用node-mongodb-native驱动程序( 即: npm install mongodb )。 Mongoose also depends on this driver, so it should be present. 猫鼬也依赖于这个驱动程序,因此应该存在。

Looking at the code directly , you have to provide your DB connection information as a MongoStore object: 直接查看代码 ,您必须提供您的数据库连接信息作为MongoStore对象:

store: new mongoStore({ host: 'session_server', port: 27017, db: 'seesion', collection: 'sessions' })

Typically for this, you'll want to have some "config" object or variable that can be dynamically loaded (dev vs test vs prod). 通常,为此,您需要一些可以动态加载的“config”对象或变量(dev vs test vs prod)。 Then you pull the host/port/db/auth off of that config object. 然后从该配置对象中拉出host / port / db / auth。

You can pass in an object of connection details (host, username, password, etc.). 您可以传入连接详细信息的对象(主机,用户名,密码等)。

You can also pass in a connection url like mongodb://user:pass@host.com/db_name. 您还可以传入连接URL,例如mongodb:// user:pass@host.com/db_name。

Both those methods will automatically start a new connection, regardless of whether or not you already have or will start a mongoose connection. 无论您是否已经拥有或将启动猫鼬连接,这两种方法都将自动启动新连接。

In the latest code, you can pass in a handle to an existing connection, an instance of mongodb.Db . 在最新的代码中,您可以将句柄传递给现有连接,即mongodb.Db的实例。 With mongoose, this would be mongoose.connection.db . 使用mongoose,这将是mongoose.connection.db However, this code isn't in an actual release, and when I tried it, it didn't work. 但是,此代码不在实际版本中,当我尝试它时,它不起作用。 Probably not ready to be used yet (or untested). 可能尚未准备好使用(或未经测试)。

I'm sure if you wait for the next release, you'll be able to pass in an existing mongoose connection. 我确定如果你等待下一个版本,你将能够传入现有的mongoose连接。 In the mean time you'll just need to accept having two connections, one from mongoose and one from connect-mongodb. 与此同时,你只需要接受两个连接,一个来自mongoose,另一个来自connect-mongodb。

I got the connection info from https://github.com/tedeh/connect-mongodb and I got the handle information from viewing the source ( relevant commit ). 我从https://github.com/tedeh/connect-mongodb获得了连接信息,我从查看源( 相关提交 )获得了句柄信息。

I just stumble across mongoose-session 我只是偶然发现了mongoose-session

Very lightweight and worked seamlessly for me. 非常轻巧,无缝地为我工作。 From github... 来自github ......

Installation 安装

npm install mongoose-session

Use 采用

var express = require('express');

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/db');

var app = express();

app.use(require('express-session')({
    key: 'session',
    secret: 'SUPER SECRET SECRET',
    store: require('mongoose-session')(mongoose)
}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM