Home > Software engineering >  How to check if a username is taken in Mongo Schema with an AJAX API call
How to check if a username is taken in Mongo Schema with an AJAX API call

Time:09-27

I am trying to create a registration form where a potential user is typing in their desired username it checks against the existing Mongo DB User Schema to see if that exact name exists.

The form I have is here:

                    <form  action="/register" method="POST" novalidate>
                      <div >
                        <p >Welcome to the team! We just need a few things to get started.</p>
                        <div >
                          <div >
                            <div >
                              <input
                                     type="text"
                                     id="first_name"
                                     name="first_name"
                                     
                                     required
                                     />
                              <label  for="first_name"
                                     >First name</label
                                >
                              <div >Looks good!</div>
                              <div >Thats not right</div>
                            </div>
                          </div>
                          <div >
                            <div >
                              <input
                                     type="text"
                                     id="last-name"
                                     name="last-name"
                                     
                                     required
                                     />
                              <label  for="last-name"
                                     >Last name</label
                                >
                              <div >Looks good!</div>
                              <div >Thats not right</div>
                            </div>
                          </div>
                        </div>
        
                      <!-- Email input -->
                      <div >
                        <input
                               type="email"
                               id="register_email"
                               name="register_email"
                               
                               required
                               />
                        <label  for="register_email">Email</label>
                        <div >Looks good!</div>
                        <div >Thats not right</div>
                      </div>
                      <div >
                          <div >
                            <input type="text" id="register_username" name="register_username"  placeholder="enter your username" required />
                            <label  for="register_username">Username</label>
                            <div id="username-check"></div>
                          </div>
                          <!-- Password input -->
                          <div >
                            <input type="password"  id="register_password" name="register_password"  required/>
                            <label  for="register_password">Password</label>
                            
                            
                          </div>
                      </div>
                      <!-- Submit button -->
                      <div >
                          <button type="submit" id="register"  disabled>
                        Lets Go! <i ></i>
                      </button>
                      </div>
                      
                    </form>

I have this script code working on the page to take the user input and check to a get route that should be checking my MongoDB:

$('#register_username').on('keyup', function () {
  $.get('/usercheck?username='   $(this).val().toLowerCase(), function (response) {
    $('#username-check').text(response.message);
    console.log('')
    var btn = document.getElementById('register');
    btn.disabled = true;
  

    if ($('#username-check').html() === "user exists") {
      $('#username-check').text('username not available').css('color', 'red');
    }
    else {
      console.log($('#register_username').val())
      $('#username-check').text('username is available').css('color', 'green');
        btn.disabled = false;
      
    }
  })
});

This is the route it calls to check the database:

var express     =   require("express"),
    router      =   express.Router(),
    passport    =   require("passport"),
    User        =   require("../models/user");

router.get('/usercheck', function(req, res) {
    console.log(req.query);
    User.findOne({username: req.query.register_username}, function(err, username){
        if(err) {
          console.log(err);
        }
        var message;
        if(username) {
          console.log(username);
            message = "user exists";
            console.log(message);
        } else {
            message= "user doesn't exist";
            console.log(message);
        }
        res.json({message: message});
    });
});
module.exports = router;

In case this helps, this is the user Schema in the database:

var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var UserSchema = new mongoose.Schema({
   username: String,
   password: String,
   email: String,
   isAdmin: { type: Boolean, default: false }
});

UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model("User",UserSchema);

I am not sure what I am missing but anything would be extremely helpful. Thanks in advance!

CodePudding user response:

Just so this question can be closed successfully: Changing /usercheck?username= to /usercheck?register_username= did the trick, because this query param was used in the form:

$('#register_username').on('keyup', function () {
  $.get('/usercheck?register_username='   $(this).val().toLowerCase(), function (response) {
    $('#username-check').text(response.message);
    console.log('')
    var btn = document.getElementById('register');
    btn.disabled = true;
  

    if ($('#username-check').html() === "user exists") {
      $('#username-check').text('username not available').css('color', 'red');
    }
    else {
      console.log($('#register_username').val())
      $('#username-check').text('username is available').css('color', 'green');
        btn.disabled = false;
      
    }
  })
});
  • Related