connect-mongo模块

本文介绍了如何使用connect-mongo工具将session数据持久化存储到MongoDB中,以避免因系统故障导致的数据丢失。该工具支持多种Node.js版本及MongoDB版本,并提供了详细的配置选项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简述:    

    session数据存储空间一般是在内存中开辟的,那么在内存中的session显然是存在极大的数据丢失的隐患的,比如系统掉电,所有的会话数据就会丢失,如果是证券交易所那么这种后果的严重性可想而知。所以为了解决这个问题可以将session持久化保存,比如保存到数据库。那么这篇博客就是介绍session持久化保存到mongoDB的工具connect-mongo。

connect-mongo介绍:

    正如上面所言,connect-mongo用于将session持久化到mongodb数据库。

    兼容性:
  • Support Express up to 5.0
  • Support all Connect versions
  • Support Mongoose >= 2.6, 3.x and 4.x
  • Support native MongoDB driver >= 1.2, 2.x
  • Support Node.js 0.10, 0.12, 4.x, 5.x, 6.x and all io.js versions
  • Support MongoDB up to 3.2

connect-mongo使用:

express框架中使用如下:

    ①在express4.x和5.0使用如下:

const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
 
app.use(session({
    secret: 'foo',
    store: new MongoStore(options)
}));


    ②express2.x和3.x如下:

const MongoStore = require('connect-mongo')(express);
 
app.use(express.session({
    secret: 'foo',
    store: new MongoStore(options)
}));

配置说明:(下一行为上一行的翻译)
  • db Database name OR fully instantiated node-mongo-native object
  • db 数据库名称
  • collection Collection (optional, default: sessions)
  • collection 集合名称,默认为sessions
  • host MongoDB server hostname (optional, default: 127.0.0.1)
  • 数据库地址,默认为本机
  • port MongoDB server port (optional, default: 27017)
  • 数据库端口,默认为27017
  • username Username (optional)
  • password Password (optional)
  • auto_reconnect This is passed directly to the MongoDB Server constructor as the auto_reconnect option (optional, default: false).
  • ssl Use SSL to connect to MongoDB (optional, default: false).
  • url Connection url of the form: mongodb://user:pass@host:port/database/collection. If provided, information in the URL takes priority over the other options.
  • mongoose_connection in the form: someMongooseDb.connections[0] to use an existing mongoose connection. (optional)
  • stringify If true, connect-mongo will serialize sessions using JSON.stringify before setting them, and deserialize them with JSON.parse when getting them. (optional, default: true). This is useful if you are using types that MongoDB doesn't support.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值