-
Notifications
You must be signed in to change notification settings - Fork 338
Expand file tree
/
Copy pathmongoose-multiple-connections.js
More file actions
70 lines (59 loc) · 1.63 KB
/
mongoose-multiple-connections.js
File metadata and controls
70 lines (59 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const express = require('express')
const mongoose = require('mongoose')
const session = require('express-session')
const MongoStore = require('connect-mongo')
const { getMongoConfig } = require('./shared/mongo-config')
const app = express()
const port = 3000
const {
mongoUrl,
mongoOptions,
dbName,
sessionSecret,
cryptoSecret
} = getMongoConfig()
const appDbUrl = process.env.APP_MONGO_URL || mongoUrl
const appDbName = process.env.APP_DB_NAME || `${dbName}-app`
const appConnection = mongoose.createConnection(appDbUrl, {
dbName: appDbName,
...mongoOptions
})
const sessionConnection = mongoose.createConnection(mongoUrl, {
dbName,
...mongoOptions
})
const sessionInit = (client) => {
app.use(
session({
store: MongoStore.create({
client,
dbName,
mongoOptions,
...(cryptoSecret ? { crypto: { secret: cryptoSecret } } : {})
}),
secret: sessionSecret,
resave: false,
saveUninitialized: false,
cookie: { maxAge: 24 * 60 * 60 * 1000 }
})
)
}
async function bootstrap() {
await Promise.all([appConnection.asPromise(), sessionConnection.asPromise()])
console.log('Connected to AppDB and SessionsDB.')
const mongoClient = sessionConnection.getClient()
sessionInit(mongoClient)
const router = express.Router()
router.get('/', (req, res) => {
req.session.foo = 'bar'
res.send('Session Updated')
})
app.use('/', router)
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
}
bootstrap().catch((err) => {
console.error('Unable to initialize Mongo connections', err)
process.exitCode = 1
})