Verify if the user is already present in the MongoDB database and authenticated with Passport

I'm currently exploring the usage of passport and I am in the process of setting up a "register" page functionality. The registration process is working smoothly, along with the log-in form. Yet, I am looking to implement a validation to check if the username entered already exists in the system. In case of a duplicate username, I aim to provide an error message to the user. Below is the snippet of code I have developed 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("/");
        });
    });
 }
    })
});

My goal is to notify the user with an error message if they attempt to register with a username that already exists within the system.

Answer №1

This is an example of how it could be rendered.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Accordions in Jquery to dynamically adjust page height during ajax calls

I am currently using AJAX to call in a page and animate its height successfully. However, I have encountered an issue with an accordion-like function that is supposed to toggle the visibility of an element and adjust the height of the containing element ac ...

Scrolling using JavaScript's 'smooth scrolling' feature is currently disabled

Background of the Issue: I am in the process of creating a one-page website using Twitter Bootstrap 3 within an ASP.NET MVC project. The Challenge: My current challenge involves implementing 'smooth scrolling' functionality that scrolls to the ...

How to combine two tables in Sequelize using a one-to-many relationship

I'm currently working with two models: User and Foto. In my application, each User can have multiple fotos, and each foto is associated with only one user. My challenge lies in using the include function. I am able to use it when querying for the us ...

Finding your way to a particular section within a webpage through an external source

Hey there! I'm currently working on creating a link that will direct users to a specific section within my webpage. For example, redirecting them to https://blabla.github.io/my-website. My code is quite straightforward and it functions properly when ...

Is there a way to dynamically adjust the form action based on whether or not JavaScript is enabled?

Is there a way to make a form default to calling a JavaScript ajax function for output, but switch to a PHP page if the user doesn't have JavaScript enabled? <form class="form-inline" role="form" action="javascript:search();"> <div class=" ...

Can Angular JS apply the uppercase filter to a boolean value?

My Angular 1.4.12 binding looks like this: {{ mob.mobDataSettings[7].value | uppercase }} The first part is a boolean value from a JSON file, which can be either true or false. But when rendered in HTML, it is not showing up as uppercase (e.g. TRUE), in ...

Dynamic loading of JavaScript/HTML content using jQuery Mobile and PhoneGap

I am currently in the process of building a mobile app using Dreamweaver CS6 (with PhoneGap), along with jQuery Mobile and JavaScript. This app aims to gather user-inputted form data, convert it into a JSON object, and send it to a python web service. The ...

Utilize [markdown links](https://www.markdownguide.org/basic-syntax/#

I have a lengthy text saved in a string and I am looking to swap out certain words in the text with a highlighted version or a markdown link that directs to a glossary page explaining those specific words. The words needing replacement are contained within ...

Converting SHA1 function from JavaScript to Python

Can you help with translating this Javascript code to Python? def sha1(str1, raw): hexcase = 0 chrsz = 8 str1 = utf16to8(str1) def utf16to8(str): out = "" len = len(str) i = 0 while i < len: ...

Learn the best practices for sharing .env values from the main project component to various reusable npm installed components

In recent projects I've worked on using React and Vue.js, I have utilized .env variables to store API URLs for micro services and other configuration settings that are used throughout the root project. However, when it comes to child components insta ...

Angular directive preventing default action but Chrome still loading image on drag

Has anyone encountered an issue with an angular directive that is not successfully preventing Chrome's default action? Below is the code for the directive in question: app.directive('fileDrag', function () { return { restrict: ' ...

Drop down menus fail to appear after the screen has been resized

Creating responsive menus involves using ordered and unordered lists, along with CSS for styling. I have added a script to dynamically generate dropdown menus, but encountered an issue where nothing appears on the screen upon resizing - only the backgrou ...

Frontend Axios request fails to retrieve necessary data from MongoDB backend database

Reaching out to the backend to retrieve posts from a mongoDB database. Successful in postman but encountering a custom error on the frontend. Puzzled as to why it's not functioning properly. Utilizing Redux to fetch user information for ...

conceal specific language options within the dropdown selection box

In my user interface, I have implemented a drop-down menu that allows users to select their preferred language. I want the selected language option to disappear from the drop-down menu once chosen. Here is the HTML code snippet: <li> < ...

Using private members to create getter and setter in TypeScript

Recently, I developed a unique auto getter and setter in JavaScript which you can view here. However, I am currently unsure of how to implement this functionality in TypeScript. I am interested in creating an Object Oriented version of this feature if it ...

execute php sql after a certain delay

Currently, I am working with PHP, SQL, and JavaScript to develop a friend request system. In this system, if User-1 sends a friend request to User-2, User-2 must accept the request within 1 hour. If not, the request will be automatically denied or removed. ...

How to add a document into a nested array in MongoDB without specifying the index position

I need to insert an item into the boardItems array within an item that has a specific boardId in my nested array based on certain property conditions: Here is the structure of my document: { name: "Foo", boardBucket: { currentBoardId: 1234, i ...

Tips for testing a mapbox popup using jasmine testing?

I encountered an issue with my mapbox popup while using jasmine and attempting to write a unit test for it. Here is the function in question: selectCluster(event: MouseEvent, feature: any) { event.stopPropagation(); this.selectedCluster = {geo ...

Issue with reactivity in Laravel and Inertia.js using Vue3

Is it possible that the reactivity of Vue is being blocked by Inertia.js page components? Within my Page component, there is a single file component. I have a function that adds items to the ItemsManager.items object. When I run this function, the single ...

Detecting server errors in Nuxt.js to prevent page rendering crashes: A Vue guide

Unique Context This inquiry pertains to a previous question of mine, which can be found at this link: How to handle apollo client errors crashing page render in Nuxt?. However, I'm isolating the focus of this question solely on Nuxt (excluding apollo ...