forked from Techie-Qabila/fastify-mongoose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
38 lines (31 loc) · 817 Bytes
/
index.js
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
'use strict'
const fp = require('fastify-plugin')
const Mongoose = require('mongoose')
const Bluebird = require('bluebird')
const ObjectId = Mongoose.Types.ObjectId
function fastifyMongoose (fastify, options, next) {
const uri = options.uri
delete options.uri
const opt = Object.assign({}, options, {
promiseLibrary: Bluebird,
useMongoClient: true
})
Mongoose.Promise = Bluebird
Mongoose.connect(uri, opt)
.then(() => {
const mongo = {
db: Mongoose.connection,
ObjectId: ObjectId
}
fastify
.decorate('mongo', mongo)
.addHook('onClose', function (fastify, done) {
fastify.mongo.db.close(done)
})
next()
},
err => {
if (err) return next(err)
})
}
module.exports = fp(fastifyMongoose, '>=0.29.0')