mongodb 基于电子邮件创建用户角色

qfe3c7zg  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(178)

大家好,我有一个MERN堆栈项目,在这个项目中用户可以注册,登录,并做一些CRUD操作。
我想让用户角色基于用户注册后的电子邮件。如果用户注册的电子邮件为example@bsi.com,我想让该用户角色为admin,但如果用户登录的电子邮件为example@gmail.com,用户角色为User。我该怎么做,我已经尝试过,但我得到错误500。
或者有其他的方法/逻辑来实现这一点吗?
索引. 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,
      });
    });
});
xytpbqjk

xytpbqjk1#

我认为mongoose构造函数不支持$cond,请尝试通过代码检查条件:

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

相关问题