Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
nodejs mongoose - how to check items in the database before login

In my project, I've different roles (seller/user/admin)and i want to check the role and redirect to specific page if they are seller for example.

I struggle on how i can check the role in Mongo DB before the login. My login page is basic email-password and submit button.

for my signup all is good, it's use the correct model and post it in the DB.

here are some pieces of my code:

(client model)

userSchema.statics.login = async function (email, password, role) {
  const user = await this.findOne({ email });

  if (user) {
    const auth = await bcrypt.compare(password, user.password);

    if (auth) {
      return user;
    }
    throw Error("incorrect password");
  }

  throw Error("incorrect email");
};

const ClientModel = mongoose.model("client", userSchema, "users");

login controller:

module.exports.clientSignIn = async (req, res) => {
  const { email, password } = req.body;
  
  try {
    const user = await LoginModel.login(email, password);
    const token = createToken(user._id);
    res.cookie("jwt", token, { httpOnly: true, maxAge });
    res.redirect('/success');
  } catch (err) {
    console.log(err.message);
  }
};

thanks in advance for your help, if you need more info please feel free to ask

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Following @EAzevedo 's advice.

i just change my Controller

module.exports.clientSignIn = async (req, res) => {
  const { email, password } = req.body;

  try {
    const user = await LoginModel.login(email, password);
    const token = createToken(user._id);
    res.cookie("jwt", token, { httpOnly: true, maxAge });
    if (user.role == "client") {
      res.redirect("/success");
    } else if (user.role == "technicien") {
      res.redirect("/success-technicien");
    } else if (user.role == "superuser") {
      res.redirect("/success-admin");
    };
  } catch (err) {
    const errors = signInErrors(err);
    res.status(200).json({ errors });
  }
};
about 4 years ago · Juan Pablo Isaza Report

0

when you get the user , you should have field for the role , then check which role logged in and redirect him to where he needs to be

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!