简体   繁体   中英

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("/");
                });
            });
      }
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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