koa session store in mongodb

Koa implements session to save mongodb casesCopy the code

Because of this module dependencykoa-session, first installkoa-session

npm install koa-session
Copy the code

Load the module in the startup file

const session = require('koa-session'); const SessionStore = require('./core/sessionStore'); // The sessionStore.js file is stored in the root directory of coreCopy the code

Configuration of the session

app.keys = ['some secret hurr']; // session configuration information const CONFIG = {key: 'koa:sess', maxAge: 86400000, overwrite: true, httpOnly: true, signed: true, rolling: false, }; Use (session(CONFIG, app));Copy the code

Set session to save mongodb

The above configuration does not save session information in mongodb, so continue…

If you want to save session information to the database, you can do it yourself:Copy the code

Github.com/koajs/sessi…

Add the store parameter to CONFIG:

const CONFIG = { key: 'koa:sess', maxAge: 86400000, overwrite: true, httpOnly: true, signed: true, rolling: False, store: new SessionStore({collection: 'navigation', // database set connection: Mongoose, // database link instance Expires: 86400, // The default time is 1 day name: 'session' // the name of the table that holds the session})};Copy the code

Test and use sessions

You can get sessions where you want them

demo:

App. use(async (CTX, next) => {// Get session object const session = ctx.session; Session. userInfo = {name:'anziguoer', email:'[email protected]', age: 28} next(); })Copy the code

Next you check to see if the mongodb database holds the values you want

Sessionstore.js file source, you can copy the code to any directory in your project, as long as you save the reference correctly

const schema = { _id: String, data: Object, updatedAt: { default: new Date(), expires: 86400, // 1 day type: Date } }; export default class MongooseStore { constructor ({ collection = 'sessions', connection = null, expires = 86400, name = 'Session' } = {}) { if (! connection) { throw new Error('params connection is not collection'); } const updatedAt = { ... schema.updatedAt, expires }; const { Mongo, Schema } = connection; this.session = Mongo.model(name, new Schema({ ... schema, updatedAt })); } async destroy (id) { const { session } = this; return session.remove({ _id: id }); } async get (id) { const { session } = this; const { data } = await session.findById(id); return data; } async set (id, data, maxAge, { changed, rolling }) { if (changed || rolling) { const { session } = this; const record = { _id: id, data, updatedAt: new Date() }; await session.findByIdAndUpdate(id, record, { upsert: true, safe: true }); } return data; } static create (opts) { return new MongooseStore(opts); }}Copy the code

Reference Documents: