From 5c664ffd41238ef53ae32f9dd6886fbd9454a021 Mon Sep 17 00:00:00 2001 From: mattkins Date: Wed, 23 Oct 2019 15:21:08 -0500 Subject: [PATCH] Resolved deprecation warnings for useNewUrlParser and useUnifiedTopology by implementing those options on mongoose.connect. Moved mongoose.Promise = Bluebird outside of the plugin declaration to ensure that it's set first thing and avoid mPromise deprecation warnings --- index.js | 57 +++++++++++++++++++++++++++++++++----------------------- 1 file changed, 34 insertions(+), 23 deletions(-) diff --git a/index.js b/index.js index 4a8c677..cd95c33 100644 --- a/index.js +++ b/index.js @@ -1,37 +1,48 @@ 'use strict' const fp = require('fastify-plugin') -const Mongoose = require('mongoose') +const mongoose = require('mongoose') const Bluebird = require('bluebird') +const ObjectId = mongoose.Types.ObjectId -const ObjectId = Mongoose.Types.ObjectId +mongoose.Promise = Bluebird function fastifyMongoose (fastify, options, next) { const uri = options.uri delete options.uri const opt = Object.assign({}, options, { - promiseLibrary: Bluebird + promiseLibrary: Bluebird, + useNewUrlParser: true, + useUnifiedTopology: 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) - }) + mongoose.connect(uri, opt) + .then( + () => { + + mongoose.connection.on('error', err => { + console.log('Mongoose connection error', err) + }); + + const mongo = { + db: mongoose.connection, + ObjectId: ObjectId + } + + fastify + .decorate('mongo', mongo) + .addHook('onClose', function (fastify, done) { + fastify.mongo.db.close(done) + }) + + next() + }) + .catch( + err => { + console.log('Error connecting to MongoDB', err) + next(err) + } + ) } -module.exports = fp(fastifyMongoose, '>=0.29.0') +module.exports = fp(fastifyMongoose, '>=0.29.0') \ No newline at end of file