一、使用mongoose链接数据库
'use strict';const mongoose = require('mongoose');const config = require('config-lite')({ filename: 'default', config_basedir: __dirname, config_dir: 'config'});const chalk = require('chalk');mongoose.connect(config.url, { dbName: config.db, useNewUrlParser: true, autoIndex: false });const connect = mongoose.connection;connect.once('open', () => { console.log( chalk.green('connect db success!') );})connect.on('error', function (error) { console.error( chalk.red('Error in MongoDb connection: ' + error) ); mongoose.disconnect();});connect.on('close', function () { console.log( chalk.red('the db is disconnect ,reconnect...') ); mongoose.connect(config.url, { server: { autoReconnect: true } });});module.exports = connect;
二、新建一个store.js文件
const { Store } = require('koa-session2');module.exports = class extends Store { constructor(con) { super(); this.collection = con.collection('sessions'); console.log("session start "); } async get(sid) { return await this.collection.findOne({ sid }); } async set(session, opts) { try { if (!opts.sid) { opts.sid = this.getID(24); } await this.collection.findOneAndUpdate({ sid: opts.sid }, { $set: session }, { upsert: true }); } catch (error) { console.log("error", error); } return opts.sid; } async destory(sid) { await this.collection.findAndModify({ sid }, [], {}, { removed: true }); }}
三、在app.js中
const session = require("koa-session2");const sessionStore = require('./middlewares/seesionStore/store');app.use(session({ key: config.session.key, maxAge: config.session.maxAge, domain: config.session.domain, store: new sessionStore(connect)}));