Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 class="needs-validation" action="/register" method="POST" novalidate>
                      <div class="text-center mb-3">
                        <p class="lead">Welcome to the team! We just need a few things to get started.</p>
                        <div class="row">
                          <div class="col-md-6 mb-4">
                            <div class="form-outline">
                              <input
                                     type="text"
                                     id="first_name"
                                     name="first_name"
                                     class="form-control"
                                     required
                                     />
                              <label class="form-label" for="first_name"
                                     >First name</label
                                >
                              <div class="valid-feedback">Looks good!</div>
                              <div class="invalid-feedback">Thats not right</div>
                            </div>
                          </div>
                          <div class="col-md-6 mb-4">
                            <div class="form-outline">
                              <input
                                     type="text"
                                     id="last-name"
                                     name="last-name"
                                     class="form-control"
                                     required
                                     />
                              <label class="form-label" for="last-name"
                                     >Last name</label
                                >
                              <div class="valid-feedback">Looks good!</div>
                              <div class="invalid-feedback">Thats not right</div>
                            </div>
                          </div>
                        </div>
        
                      <!-- Email input -->
                      <div class="form-outline mb-4">
                        <input
                               type="email"
                               id="register_email"
                               name="register_email"
                               class="form-control"
                               required
                               />
                        <label class="form-label" for="register_email">Email</label>
                        <div class="valid-feedback">Looks good!</div>
                        <div class="invalid-feedback">Thats not right</div>
                      </div>
                      <div class="text-center mb-3">
                          <div class="form-outline mb-4">
                            <input type="text" id="register_username" name="register_username" class="form-control" placeholder="enter your username" required />
                            <label class="form-label" for="register_username">Username</label>
                            <div id="username-check"></div>
                          </div>
                          <!-- Password input -->
                          <div class="form-outline mb-4">
                            <input type="password"  id="register_password" name="register_password" class="form-control" required/>
                            <label class="form-label" for="register_password">Password</label>
                            
                            
                          </div>
                      </div>
                      <!-- Submit button -->
                      <div class="text-center">
                          <button type="submit" id="register" class="btn btn-lg btn-rounded bg-insider link-dark mb-3 fw-bold" disabled>
                        Lets Go! <i class="fa-solid fa-gauge-max"></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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$('#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!

>Solution :

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;
      
    }
  })
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading