In my project there are many database, one is masterDb and all other are database connect based on the masterDb. For example , in the verification page the user can enter a 'company id', this 'company id' can be checked with the masterDb and if an id exist it then return the database name for the specific company. Using the database name i want to connect to the specific company database.
Now i can successfully login and i get the db name. Using this db name (req.headers['x-key-db']) i can connect to the specific database. but here i place the database connection code inside every api call. Is there any another way to create it once and use it in every api call dynamically.
app.get('/api/student-limited/:_pageNumber/:_pageSize', function(req, res) {
var db = mongoose.createConnection();
db.open('mongodb://localhost:27017/'+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});
});
}
});
});