node.js - i want to connect db dynamically when user login nodejs mongodb -


please me out of it. login api want set mongoose connection string. possible login api set connection string , works other api also(which call after login api)?? first user login @ time set db , further api call works db? had tried how connect multiple mongodb database dynamically using mongoose? in solution in each api specifies requested param. can set connection string of mongo api call?

this app.js

 var mongoose = require('mongoose');     var connections = [test = mongoose.createconnection('mongodb://localhost:27017/test'),  demo = mongoose.createconnection('mongodb://localhost:27017/demo')];      exports.getdatabaseconnection = function (dbname) {        if (connections[dbname]) {         //database connection exist. return connection object         return connections['dbname'];       } else {         connections[dbname] = mongoose.createconnection('mongodb://localhost:27017/' + dbname);         return connections['dbname'];       }     } 

and user.js

exports.authenticate = function (req, res) {  var db = app.getdatabaseconnection(req.body.keydb);  var userdetail = db.model('userdetail', userschema);     userdetail.findone({     email: req.body.email,     usertype: req.body.usertype   }, function (err, user) {     if (err) throw err;     if (!user) {       res.send({ status: 400, message: req.i18n.__("user.authincorrectemail") });     } else {...} }); } 

when requesting keydb value demo..then should select demo string in connection array. not working.what doing wrong??

i trying connect mongodb per user login request comes. want set db once not on each api call. if user logout db should disconnect , when again user login should again connect.

you need keep list of database connections, 1 per session. 1 way have object keys session ids , values database connections. alternatively can keep 1 connection per user id if want allow situation same user has multiple sessions , each share database connection. when create session on user login create new database connection. when destroy session on user logout have close connection , remove object stored. other endpoints except login , logout connection , use it.

this how can achieve goal keep in mind keeping separate database connection per logged in user has many disadvantages , wastes lot of resources, both in application , in database.

can set connection string of mongo api call?

yes, of course. mean people able trick app e.g. breaking other people's databases , responsible of legal consequences of that.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -