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);
});
});