简体   繁体   English

检查 mongodb 和护照中是否已经存在用户

[英]Check if user already exists in mongodb and passport

I'm new to passport and I'm trying to create a "register" page.我是护照新手,我正在尝试创建一个“注册”页面。 This actually works fine, and the log-in form as well.这实际上工作正常,登录表单也是如此。 However, I want to check if the username entered already exists, and if it does, throw an error to the user.但是,我想检查输入的用户名是否已经存在,如果存在,则向用户抛出错误。 Here is my code so far:到目前为止,这是我的代码:

expressApp.post("/register", function(request, response){

User.findOne({username: request.body.username}, function(err, user) {
        if (err) {
            return err;
        }
        if (user) {

        }
     else {

    User.register(new User({
        username: request.body.username,
        type: "Student"}),
        request.body.password, function(err){
        if(err){
            console.log(err);
        }
        passport.authenticate("local")(request, response, function(){
            response.redirect("/");
        });
    });
 }
    })
});

However, If someone chooses a username that already exists, then i want to be able to tell them that there is an error.但是,如果有人选择了一个已经存在的用户名,那么我希望能够告诉他们有错误。

It should look something like this.它应该看起来像这样。

expressApp.post("/register", function(request, response) {

  User.findOne({
    username: request.body.username
  }, function(err, user) {
    if (err) {
        return err
    } else if (user) {
        //user.message = "User already exists!!"
        response.statusCode = 409
        return response.send({"message": "User already exists!!")
    } else {
        User.register(new User({
                username: request.body.username,
                type: "Student"
            }),
            request.body.password,
            function(err) {
                if (err) {
                    console.log(err);
                }
                passport.authenticate("local")(request, response, function() {
                    response.redirect("/");
                });
            });
      }
   });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM