Hello Friends!
For my project I’m Using Express , NodeJS and Mongoose . My Application structure is that Every Client has his own DB (In my same atlas cluster) And Each Client has its Own collections .
Each Client Has Its Own Users Collection And some other collections . I thought about creating a function ,using .find() ,and it will run for all of my DB’S (Clients) to determine Which DB the requesting user(when logging in) belongs to and then create his connection to the Relevant DB .
I will be happy for a “smarter” suggestions to Solve my issue Thanks!
My application currently running with only one DB (Client) and I want to expand it as I Explained above , My current Code for connection is :
mongoose.connect(MongoUrl,
{ useNewUrlParser: true, useUnifiedTopology: true})
.then(()=> {
console.log('DB Connection, Successful')
})
.catch(err => {
console.log('Error connecting DB')
console.log(err)
})
For Authentication Im using PassportJS (passport-local-mongoose)
I Tried this way , Inside login post request :
// this will run, connect to the correct DB
await findUser(req).catch(console.error);
// then authenticate as i did previously while i had only one db
await passport.authenticate('local', {failureFlash:true ,failureRedirect: '/login' })
console.log(req.user)
and it calls this function :
let relevantDB
let Fuser
async function findUser(req) {
const uri = MongoUrl;
const client = new MongoClient(uri);
try {
await client.connect();
const db1 = client.db('test')
const db2 = client.db('test2');
let db1_users = db1.collection('users')
let db2_users = db2.collection('users')
// Find the first document in the collection
const first = await db1_users.findOne({username: req.body.username});
const second = await db2_users.findOne({username: req.body.username});
if (first) {
relevantDB = 'gym1'
Fuser = first
}
if (second) {
relevantDB = 'gym2'
Fuser = second
}
} finally {
// Close the database connection when finished or an error occurs
if (relevantDB === 'gym1') {
console.log('arrived gym1')
// MongoDB Connection
await mongoose.connect(gym1,
{ useNewUrlParser: true, useUnifiedTopology: true})
.then(()=> {
console.log('DB Connection, Successful')
})
.catch(err => {
console.log('Error connecting DB')
console.log(err)
})
}
if (relevantDB === 'gym2') {
// MongoDB Connection
mongoose.connect(gym2,
{ useNewUrlParser: true, useUnifiedTopology: true})
.then(()=> {
console.log('DB Connection, Successful')
})
.catch(err => {
console.log('Error connecting DB')
console.log(err)
})
}
await client.close();
}
}
a User Found , then the correct DB is connected but the req.user isnt created … req.user is undefined