多租户和猫鼬

问题描述 投票:0回答:0

作为我之前帖子的延续:建立组织结构 我的数据库结构是: CentralDB:它有我的用户、会话和组织 Organization1 数据库(少量集合) Organization2 DB(相同的几个集合)

我的目标是隔离每个组织数据并基于我的 PassportJS 本地身份验证 - 基于用户组织关联为相关数据库创建连接池。

在我的主要 js 文件中: 我正在为 Auth 创建到 CentralDB 的连接:

// MongoDB Connection
const centralDB = mongoose.createConnection(MongoUrl,{useNewUrlParser: true, useUnifiedTopology: true}, (error,connection)=> {
    if (error) {
        console.error("Error connecting CentralDB:", error);
    } else {
        console.log("Connected to CentralDB!");
    }
})
exports.centralDB = centralDB
const User = centralDB.model('User', require('./models/users'))
exports.User = User;
app.use(passport.initialize());
app.use(passport.session());
// use static authenticate method of model in LocalStrategy
passport.use(new LocalStrategy(User.authenticate()));

// use static serialize and deserialize of model for passport session support
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
  • 我正在导出用户模型以在其他路由中访问它

登录路线:

.post(passport.authenticate('local', {failureFlash:true ,failureRedirect: '/login' }),
async function(req, res) {
    const find_user = await mainfile.User.findById(req.user._id).populate({path: 'organization',model:Organization})
    req.session.connectionString = find_user.organization.connectionString
    const connectionStream = mongoose.createConnection(req.session.connectionString,{useNewUrlParser: true, useUnifiedTopology: true}, (error,connection)=> {
      if (error) {
          console.error("Error connecting DB:", error);
      } else {
          console.log(`Connected to ${req.user.organization}`);
      }
   })
   req.session.dbname = find_user.organization.name
    const redirectUrl = req.session.returnTo || '/';
    delete req.session.returnTo;
  res.redirect(redirectUrl);
})

我在这里创建一个新的连接 - 基于用户的组织 然后在 My / (Main dashboard/homepage) Route 中: 我根据创建的新连接定义模型 *注意这里 - 我试图在我的登录路线中声明模型,但我无法将它们导出到我的其他路线..

// Home Page 
app.get('/',catchAsync(async (req,res) => {
    var user = null
    var programs = null
    var sum_of_training = null
    var trainers = null
    var trainees = null
    if (req.user) {
    let index = mongoose.connections.findIndex(e=> e.name === req.session.dbname)
    const Program = mongoose.connections[index].model('Program',require('./models/my-program'))
    const Sum_Training = mongoose.connections[index].model('Sum_Training',require('./models/sum_of_training')) 
    const Exercise = mongoose.connections[index].model('Exercise', require('./models/exercises'))
    const superSet = mongoose.connections[index].model('superSet', require('./models/superset'))
    const trainee_exercises = mongoose.connections[index].model('trainee_exercise',require('./models/user_exercise'))
    module.exports.trainee_exercises = trainee_exercises
    module.exports.Program = Program
    module.exports.Exercise = Exercise
    module.exports.Sum_Training = Sum_Training
    module.exports.superSet = superSet
    var user = await User.findById(req.user._id).populate({path:'programs',model: Program})
    var trainers = await User.find({isTrainer: true})
    var trainees = await User.find({isTrainer: false})
    if (req.user.isTrainer === true) {
    var sum_of_training = await Sum_Training.find({}).populate({path: 'program_id',populate: {
      path: 'author',model: User
  }}).limit(3).sort({date: 'desc'}).exec()
}
if (req.user.isManager === true) {
    var programs = await Program.find({}).populate({path:'program_for',model: User}).limit(3).sort({d_t: 'desc'}).exec()
} else {
    var programs = await Program.find({"author": `${req.user._id}`}).populate({path: 'program_for',model: User,populate:{path: 'organization',model: Organization}}).limit(3).sort({d_t: 'desc'})

}
}
    res.render('home', { user ,programs,sum_of_training,trainers,trainees})
}))

问题是当第二个用户登录时(关联到不同的组织) - 它超过了第一个连接并且第一个用户正在访问用户 2 db

我知道问题是因为我在我的 / 路线中声明模型,但我找不到正确的方法

谢谢

node.js mongodb express mongoose multi-tenant
© www.soinside.com 2019 - 2024. All rights reserved.