agmission/Development/shared/db-util/mongoose-connect.js

53 lines
1.9 KiB
JavaScript

module.exports = function (options) {
const
debug = console.log, //require('debug')('agm:db'),
mongoose = require('mongoose');
// Our custom middleware
mongoose.Promise = global.Promise; // Disable Promise depreciated warning
options = options || { poolSize: 5, debugMode: false };
const opts = {
user: 'agm', pass: 'Agm2017',
connectTimeoutMS: 40000,
// TCP Connection timeout setting. Best = 2-3X time of longest operation (30 minutes)
socketTimeoutMS: 30 * 60 * 1000,
// The number of milliseconds to wait before initiating keepAlive on the TCP socket.
keepAlive: true, keepAliveInitialDelay: 30000,
// for better performace in Production invironment
autoIndex: false,
poolSize: options.poolSize, // Default 5
useNewUrlParser: true,
useFindAndModify: false,
useCreateIndex: true,
useUnifiedTopology: true,
family: 4
}
mongoose.set('bufferCommands', false); // Disable buffering globally
mongoose.connect('mongodb://localhost:27017/agmission?authSource=agmission', opts);
mongoose.connection.on('disconnected', () => { debug('-> MongoDB lost connection'); });
mongoose.connection.on('reconnect', () => { debug('-> MongoDB reconnected'); });
mongoose.connection.on('connected', () => { debug('-> MongoDB connected'); });
mongoose.connection.on('reconnectFailed', () => { debug('-> MongoDB gave up reconnecting'); });
mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection errors:'));
if (options.debugMode) mongoose.set('debug', true);
function postExit() {
if (mongoose.connection) {
mongoose.connection.close(() => {
debug('Mongoose default connection disconnected through app termination');
process.exit(0);
});
} else {
process.exit(0);
}
}
// If the Node process ends, close the Mongoose connection
process.on('SIGINT', function () { // Windows
postExit();
});
return mongoose.connection;
}