Reuse of connections on Nodejs + Mongoose

1

I'm now starting with Node and I used Mongoose to make my database connections to MongoDB. I put 1 log in my application, every time I open the connection it will print in this log.

What happens: Every time someone calls my URL, my Node application opens a connection to MongoDB, is this normal and correct? That is, if 1,000 are accessing my site, will there be 1000 connections open? Is there any way to improve this and avoid problems, or is this normal for this environment?

For each My Model, I have 1 code of this type:

var mongoose = require('mongoose');
var database = require('../config/database');
var mongoOptions = { db: { safe: true }};
mongoOptions.user = database.user;
mongoOptions.pass = database.pass;

console.log('Running mongoose version %s', mongoose.version);

mongoose.connect(database.url, mongoOptions, function (err, res) {
  if (err) { 
    console.log ('ERROR connecting to: ' + database.url + '. ' + err);
  } else {
    console.log ('Successfully connected to: ' + database.url);
  }
});

var Schema = mongoose.Schema;
var citySchema = new Schema({
    name: String,
    url: String,
    uf: String,
    dtRequest: Date,
    active: Boolean,
    loc: {
        type: [Number],
        index: '2dsphere'
    }
});

module.exports = mongoose.model('City', citySchema);

var db = mongoose.connection;
db.on('error', console.error);

process.on('SIGINT', function() {
  db.close(function () {
    console.log('Mongoose default connection disconnected through app termination');
    process.exit(0);
  });
});
    
asked by anonymous 12.08.2016 / 22:06

1 answer

1

The connection to the database should be in the main project file, the one that the node will execute, so the connection will only be made once.

For example, the code below is your main file, app.js, which is responsible for project routes and settings:

const express = require('express');
const database = require('../config/database');
const mongoose = require('mongoose');

const app = express();

const mongoOptions = { 
    db: { safe: true },
    user: database.user,
    pass: database.pass
};

mongoose.connect(database.url, mongoOptions, function (err, res) {
    if (err) { 
        console.log ('ERROR connecting to: ' + database.url + '. ' + err);
    } else {
        console.log ('Successfully connected to: ' + database.url);
    }
});

app.listen(8080);

The code below is your model:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const citySchema = new Schema({
    name: String,
    url: String,
    uf: String,
    dtRequest: Date,
    active: Boolean,
    loc: {
        type: [Number],
        index: '2dsphere'
    }
});

module.exports = mongoose.model('City', citySchema);

When you run an node app.js the connection will be started only once, and will remain so until the process is terminated or an error occurs.

    
13.08.2016 / 04:22