node.js + express.js:使用 mongodb/mongoose 处理会话
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6819911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
node.js + express.js: session handling with mongodb/mongoose
提问by pkyeck
Right now i'm storing my session data in the "memory store" which comes bundled with connect(express). But I want/have to change this for production.
现在,我将会话数据存储在与 connect(express) 捆绑在一起的“内存存储”中。但是我想/必须为生产更改此设置。
The application is using mongodb and I installed mongoose to handle all db-communications.
该应用程序使用 mongodb,我安装了 mongoose 来处理所有数据库通信。
e.g. 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? I need to add something like this:
我找到了 connect-mongodb 模块,但我不知道如何使用 mongoose 来实现它,或者它是否真的可能实现?我需要添加这样的东西:
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 再次定义我的数据库连接?
回答by pkyeck
in the end i'm using a bit of every answer that was given before:
最后,我使用了之前给出的每个答案的一些内容:
- i switched from connect-mongodb to connect-mongo module
- i'm using a general conf object to store my configuration data
- 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)
- 我从 connect-mongodb 切换到 connect-mongo 模块
- 我正在使用一个通用的 conf 对象来存储我的配置数据
- 有两个 db 连接,因为它对我来说更容易处理(如果/当新版本的猫鼬/express 出现时可能会更改)
requirements:
要求:
var express = require('express'),
MongoStore = require('connect-mongo')(express),
mongo = require('mongoose');
conf object:
配置对象:
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);
});
回答by Raja
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
类型错误:无法读取未定义的属性“connect.sid”
回答by Peter Lyons
It looks like you could do this to setup connect-mongodbassuming your mongoose connection code above is run earlier:
connect-mongodb假设上面的猫鼬连接代码更早运行,您似乎可以这样做:
app.use(express.session({
secret: 'topsecret',
maxAge: new Date(Date.now() + 3600000),
store: new mongoStore({ db: mongoose.connections[0].db })
}));
回答by Gates VP
So connect-mongodbdoes not use Mongoose, it uses the node-mongodb-nativedriver (i.e.:npm install mongodb). Mongoose also depends on this driver, so it should be present.
所以connect-mongodb不使用 Mongoose,它使用node-mongodb-native驱动程序(即:)npm install mongodb。Mongoose 也依赖于这个驱动程序,所以它应该存在。
Looking at the code directly, you have to provide your DB connection information as a MongoStoreobject:
直接看代码,你必须提供你的数据库连接信息作为一个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). Then you pull the host/port/db/auth off of that config object.
通常为此,您需要一些可以动态加载的“配置”对象或变量(开发与测试与生产)。然后从该配置对象中提取主机/端口/db/auth。
回答by Cory Klein
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);
});
sessionhas been moved to it's own module, so you need to requireit and use sessionwhen configuring the MongoStore.
session已经移动到它自己的模块,所以你需要require它,并使用session配置的时候MongoStore。
回答by Andz
You can pass in an object of connection details (host, username, password, etc.).
您可以传入连接详细信息的对象(主机、用户名、密码等)。
You can also pass in a connection url like mongodb://user:[email protected]/db_name.
您还可以传入一个连接 url,如 mongodb://user:[email protected]/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. With mongoose, this would be 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).
在最新的代码中,您可以将句柄传递给现有连接,即mongodb.Db. 对于猫鼬,这将是mongoose.connection.db. 但是,此代码不在实际版本中,当我尝试时,它不起作用。可能还没有准备好使用(或未经测试)。
I'm sure if you wait for the next release, you'll be able to pass in an existing mongoose connection. 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-mongodband I got the handle information from viewing the source (relevant commit).
我从https://github.com/tedeh/connect-mongodb获得了连接信息,并通过查看源代码(相关提交)获得了句柄信息。
回答by Sean McClory
I just stumble across 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)
}));

