Home > database >  Create user role based on email
Create user role based on email

Time:10-25

Hello guys i have a MERN stack project, in this project user can register, login, and do some CRUD operations.

I want to make user role based on user email after they register. If the user register with email [email protected] i want to make that user role as admin, but if the user login with [email protected] the user role is User. How do i do that, i already tried but im getting error 500.

Or is there another way/logic of implementing this ?

index.js :

app.post("/register", async (req, res) => {
    bcrypt
    .hash(req.body.password, 10)
    .then((hashedPassword) => {
      // create a new user instance and collect the data
      const user = new UserModel({
        email: req.body.email,
        password: hashedPassword,
        role : {$cond : {if : {email : {$regex : "bsi"}}, then : "Admin", else : "User"}}
      });
      // save the new user
      user
        .save()
        // return success if the new user is added to the database successfully
        .then((result) => {
          res.status(201).send({
            message: "User Created Successfully",
            result,
          });
        })
        // catch error if the new user wasn't added successfully to the database
        .catch((error) => {
          res.status(500).send({
            message: "Error creating user",
            error,
          });
        });
    })
    // catch error if the password hash isn't successful
    .catch((e) => {
      res.status(500).send({
        message: "Password was not hashed successfully",
        e,
      });
    });
});

CodePudding user response:

I don't think that mongoose constructor supports $cond, try to check the condition via code:

const role = new RegExp('bsi', 'gi').test(req.body.email) ? 'Admin' : 'User';
const user = new UserModel({
    email: req.body.email,
    password: hashedPassword,
    role
});
  • Related