需要用到中间件
koa-session-minimal,提供koa2中session的读写接口
koa-session-mongoose,提供mongoose数据库中session数据的读写操作
示例代码
const Koa = require('koa');
const mongoose = require('mongoose');
const session = require('koa-session-minimal');
const MongooseStore = require('koa-session-mongoose');
const app = new Koa();
mongoose.connect('mongodb://localhost:27017/test',{useMongoClient:true});
app.use(session({
store: new MongooseStore()
}));
app.use(async ctx => {
const { session } = ctx;
let n = session.views || 0;
session.views = ++n;
ctx.body = `${n} view(s)`;
});
app.listen(3000)
console.log('session is starting at port 3000');