Node js cluster mongoose connection

I use nodejs, which is built into the cluster module, in my mongodb application (not plastered) used to store in each cluster a (working) connection is performed using the mongoose.createConnection method and closes after data is inserted.

But I expect that whenever a request is made, it opens a connection to db and the process request and closes the connection.

But what I noticed when I check the mongodb log is still opening the connection, and its score is slippery more than no processor / (cluster nodes).

and I add poolSize: 1, autreconect: false, yet some connections do not close even after calling the close () method.

my observations - when a connection error occurs, the connection does not close Please help me

I use the following script to get the connection.

module.exports.getDb = function () { var dburl = 'mongodb://localhost/DB'; db = mongoose.createConnection(dburl, { server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 }, auto_reconnect: false, poolSize: 1 } }, function (err) { console.log(err) }); db.on('error', function (err) { console.log(err + " this is error"); db.close(); }); return db; } 

and I will close the connection using db.close () at the end of the evey request callback.

+6
source share
1 answer

Are you looking for something like this?

 db.connection.on('error', function (e) { console.log(e + " this is error"); db.close(); }); 

For my API server, I wrote a plugin for Hapi to handle this. Take a look, this can help you.

 'use strict'; var bluebird = require('bluebird'); var mongoose = bluebird.promisifyAll(require('mongoose')); exports.register = function(plugin, options, next) { mongoose.connect(options.mongo.uri, options.mongo.options, function (e) { if (e) { plugin.log(['error', 'database', 'mongodb'], 'Unable to connect to MongoDB: ' + e.message); process.exit(); } mongoose.connection.once('open', function () { plugin.log(['info', 'database', 'mongodb'], 'Connected to MongoDB @ ' + options.mongo.uri); }); mongoose.connection.on('connected', function () { plugin.log(['info', 'database', 'mongodb'], 'Connected to MongoDB @ ' + options.mongo.uri); }); mongoose.connection.on('error', function (e) { plugin.log(['error', 'database', 'mongodb'], 'MongoDB ' + e.message); }); mongoose.connection.on('disconnected', function () { plugin.log(['warn', 'database', 'mongodb'], 'MongoDB was disconnected'); }); }); return next(); }; exports.register.attributes = { name: 'mongoose', version: '1.0.0' }; 
0
source

Source: https://habr.com/ru/post/972559/


All Articles