Node.js uses Mongodb-native connection to connect mongodb and frequently disconnects the connection, seeking a solution?

  node.js, question

Node.js version 6.2.0, mongodb-native 2.1.20. The program will not crash, stuck in the database query location.

The code for implementing database connection is as follows:

//Call the database connection when the program starts
 mongoConnect.connect(config.mongodb.master.url, function (err, db) {
 if (err) {
 console.log(err);
 process.exit(1);
 } else {
 app.listen(config.server.port, function () {
 Log ('appserverstartat:' plus config.server.port);
 });
 
 module.exports = app;
 bracket
 });
//Connect to database
 'use strict';
 
 var MongoClient = require('mongodb').MongoClient;
 
 var mongo = {
 '_db': null,
 '_mongodbUrl': null,
 '_connectOptions': {
 'server':{
 'auto_reconnect': true,
 'poolSize': 10,
 'socketOptions':{
 'keepAlive': 1
 bracket
 },
 'db': {
 'numberOfRetries': 10,
 'retryMiliSeconds': 1000
 bracket
 },
 
 connect(mongodbUrl, callback) {
 var that = this;
 if (!  mongodbUrl) {
 reject(new Error('missing parameter "mongodbUrl"'));
 } else {
 that._mongodbUrl = mongodbUrl;
 MongoClient.connect(that._mongodbUrl, that._connectOptions, function (err, db) {
 if (err) {
 console.log(err);
 that._db = null;
 callback(err);
 } else {
 db.on('close', function () {
 console.log('mongodb server closed');
 that._db = null;
 });
 db.on('timeout', function () {
 console.log('mongodb server timeout');
 that._db = null;
 });
 db.on('error', function () {
 console.log('mongodb server closed');
 that._db = null;
 });
 
 that._db = db;
 callback(null, that._db);
 bracket
 });
 bracket
 },
 
 getInstance(callback) {
 var that = this;
 if (!  that._db) {
 console.log('reconnect to mongodb');
 that.connect(that._mongodbUrl, (err, db) => {
 if (err) {
 callback(err);
 } else {
 callback(null, db);
 bracket
 });
 } else {
 console.log('use exists mongodb instance');
 callback(null, that._db);
 bracket
 bracket
 };
 
 module.exports = mongo;
//Use database
 mongo.getInstance(function (err, db) {
 var collection = db.collection('users');
 collection.find({}).limit(10).toArray(function (err, users) {
 if (err) {
 res.send(err);
 } else {
 res.send(users);
 bracket
 });
 });

After making a mistake, I triedDoes mongoDB have reconnect issues or am i doing it wrong?Under all the solutions, there is still no solution.

Use nowgeneric-poolAs for the database connection, the disconnection frequency will be reduced, but the disconnection situation will still occur. Only restarting the service can solve the problem.

You can implement the getConnection method, return Promise, and judge whether the connection is available internally. if not, connect first and then return.