You can create a module, as shown below, that will check if there is already a database connection for the database you need. If so, it will return the connection object, otherwise it will create and return it.
var mongoose = require('mongoose');
var connections = {};
exports.getDatabaseConnection = function(dbName) {
if(connections[dbName]) {
return connections[dbName];
} else {
connections[dbName] = mongoose.createConnection('mongodb://localhost:27017/' + dbName);
return connections[dbName];
}
}
, data.js
data.js
, API. API - :
app.get('/api/student-limited/:_pageNumber/:_pageSize', function(req, res) {
var db = data.getDatabaseConnection(req.headers['x-key-db']);
var ClassSection = db.model('ClassSections', SectionSchema);
var Student = db.model('Students', StudentSchema);
var _pageNumber = parseInt(req.params._pageNumber), _pageSize = parseInt(req.params._pageSize);
Student.find({}, function (err, _docs) {
if(_docs){
Student.find({}, null, {sort: { Name: 1} }).skip(_pageNumber > 0 ? ((_pageNumber-1)*_pageSize) : 0).limit(_pageSize).populate('_idClass').exec(function (err, docs) {
if(err)
res.json(err);
else
res.json({ "TotalCount" : _docs.length, "_Array" : docs});
});
}
});
});