Home > Software design >  Which is a more reasonable way in mongodb?
Which is a more reasonable way in mongodb?

Time:02-22

there are two ways to check login, both of them are using query once

let where = {
 username
};
//check username first
let result = await UserModel.findOne(where)
if (result != null) {
 if (result.password === password) {
  return done(null, result)
 } else {
  return done(null, false, 'wrong password')
 }
} else {
 return done(null, false, 'user does not exist')
}

and

let where = {
 username,
 password
};
//check username and password
let result = await UserModel.findOne(where)
if (result != null) { 
 return done(null, result)
} else {
 return done(null, false, 'wrong password or username')
}

Which one is better and why? Thank you.

CodePudding user response:

Ask yourself this question.

let query = {
   matchValue: "someValue",
   someValue: { $gt: 1 },
   someOtherValue: { $gte: 1 }
}

const results = await model.findOne(query)

if (results) // do something

vs

let query = {
    matchValue: "someValue"
}

const results = await model.findOne(query);
if (results.someValue > 1 && results.someValue >== 1){
 ... do something.
}

If checks can be done by mongodb (more performant), why do it in javascript?

Other than performance, both of your logics work the same way, and returns the same results.

Whatever the result may be (invalid username OR password), the response to frontend should always be "Invalid username / password"

CodePudding user response:

Well, according to me you should first ask for username and if that matches the database then we should ask for password. If you ask a user for username, you should validate that user as soon as possible. Otherwise, users may make a typo in their contact info and then spend considerable time using your service only to find there is no account matching their info the next time they attempt login. These accounts are often orphaned and unrecoverable without manual intervention. Worse still, the contact info may belong to someone else, handing full control of the account to a third party.

  • Related