Searching the database to find if the username is already in use with MEAN

Help needed with signup controller code!

    app.controller('SignupController', function ($scope, $http, $window) {

        $scope.submitSignup = function () {
            var newUser = {
                username: $scope.username,
                password: $scope.password
            };

            if (newUser.username == db.users.username) {
                alert('Username already taken.');
            }

            if ($scope.submitsignup.$valid) {
                $http.post('/users', newUser).then(function () {
                    $window.location.href = '/#';
                    alert('Account created successfully!');
                });
            }
            else {
                alert('Error during registration process.');
            }
        }});

Note: Error message says db is not defined.

Server.js snippet fetching users from database:

    app.get('/users', function (req, res, next) {
        db.collection('users', function (err, usersCollection) {
            usersCollection.find().toArray(function (err, users) {
                return res.json(users);
            });
        });
});

Answer №1

My top recommendation is to explore utilizing the Node module passport for managing signups and signins, as it offers great functionality.

On the console front, the issue lies in not having access to the db variable used in your server.js. This variable is undefined on the front-end, rendering it meaningless.

One potential solution is using app.get('/users') to send a list of users from the database to the front-end. However, I advise caution as sending extensive user information may not be ideal if there are numerous users. Nonetheless, this approach will function if you conduct your check within the http.get() request.


$http.get('/users').then(function(result){
    if(result.users.find(newUser.username)){
        alert('Username is taken!');
    } else {
        //continue working
    }
}

While this method should work, it may not be the most efficient. It would be better to modify your app.get to accept a param or query, returning a boolean if found in the database instead.

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

Uncaught jQuery onchange event not firing

I am facing an issue with a drop-down list inside a data grid on the main page. When values are changed, a popup should display and the values from the popup need to be sent back to the main page. However, I am having trouble triggering the onchange event. ...

including a content tag into an input field within a template

I'm experimenting with the new html5 template tag to create a versatile form that can be used in various situations without relying heavily on javascript. Check out this fiddle to see what I have so far http://jsfiddle.net/684uH/ My objective is to ...

Managing form submissions using Material UI and Next.js

Can someone provide insights on using Material UI with Next Js? I am experimenting with a Login template from Material UI, but I am facing an issue where query params are added to the URL upon Submit. For example: localhost:3000/auth/login changes to: ...

Angular update row and save data to an array

When comparing the data of an edited row with the row just below it, I encounter a specific scenario. In a table containing 5 rows, as I edit records from top to bottom using the provided code snippet, I am able to store the values in an array. The most re ...

Obtain Data for Visualizing Graph with JSON within a Database-connected Graph (highchart.js)

In the process of creating a database-driven graph, I am utilizing libraries from Codepen. These libraries include: THIS and Highchart.js The HTML file on display simply showcases the chart, while the main data processing is handled in an index.js file t ...

How can I access the value of a textbox within a dynamically generated div?

In my project, I am dynamically creating a div with HTML elements and now I need to retrieve the value from a textbox. Below is the structure of the dynamic content that I have created: <div id="TextBoxContainer"> <div id="newtextbox1"> // t ...

Ensuring input validity and blocking changes if not compliant with AngularJS patterns

I am looking to create an input field that only accepts the values 1, 2, or 3. To achieve this, I am working on a directive that will prevent any changes to the model if it doesn't match these specific values. For example, if the value is 1 and I tr ...

"Enhance Your Video Experience with a Personalized Play Button

Is it possible to customize the play icon for an embedded YouTube video? I came across a post discussing this topic: Can I change the play icon of embedded youtube videos? However, when trying to use something transparent as the new play button, the origin ...

Email attachments not working in Node Mailgun

I am facing an issue with my code that is designed to send emails using Mailgun in Node. The code functions as expected and sends the email successfully; however, it fails to attach the specified files. // pdfA and pdfB are both buffers defined earlier le ...

Tips for accessing a composition function in VueJS from another composition

I've been diving into the new composition-api within VueJS and have encountered a problem that I need help with. I am seeking advice on how to effectively tackle this issue. Previously, when everything was vuex-based, dispatching an action to another ...

Is it possible to use a custom filter along with data-ng-model? Problem arises when attempting to bind a custom filter with data-ng-model

I have created a custom filter to format input numbers into a specific format, like hh:mm. filter app.filter('formatDuration', function () { return function (duration) { if (angular.isUndefined(duration) || duration === null || dura ...

Tips on adding background images to your chart's background

Is there a way to set an image as the background in Lightning Chart using chartXY.setChartBackground? ...

What is the best method for fetching data from PHP to display on my Angular page?

I am struggling to retrieve data from MySQL to display on my AngularJS page, using PHP as my server-side language. I can fetch the data from my PHP file but unable to render it on my page. If you have any alternative solutions, please let me know. Below i ...

Discover how to utilize images encoded in base64 format within webhook embeds on Discord

Can someone help me with inserting an image into a Discord embed using a webhook? I have the image saved as a base64 string obtained from a database. However, my attempts so far have only resulted in an empty embed. https://i.sstatic.net/CVs4j.png const d ...

Shape with a dark border div

Having some trouble with creating this particular shape using CSS border classes. If anyone can assist in making this black box shape using Jquery, it would be greatly appreciated. Check out the image here. ...

Implementing a parallax scroll effect using CSS and dynamically updating the background-position value with JavaScript

How can different Y position percentages be dynamically assigned to multiple layered background images in CSS using JavaScript so that they update as the page scrolls? <style> body { background-image: url(img/bg-pattern-01.png), ur ...

Prevent user scrolling when full-screen menu is activated

Currently, I am developing a full-screen menu for a website and facing an issue with disabling the user's ability to scroll when the menu is open. Despite searching online, I have not found a suitable solution. It would be greatly appreciated if someo ...

Look into HTML and JavaScript problems specific to IOS devices

I have encountered some HTML markup and JavaScript functionality issues on my web-app that seem to only occur on iPad and iPhone. Unfortunately, I do not have access to any iOS devices to debug these problems. How can I replicate and troubleshoot these i ...

The animation feature in Angular JS seems to be malfunctioning

Currently in the process of creating a slideshow using AngularJS, similar to the one found at this link, which includes navigation arrows (next and prev). Here is the HTML code snippet: <div class="carousel"> <div class="left"><input ty ...

Numeric value along with two characters following the decimal place

Imagine I have this number: 25297710.1088 My goal is to add spaces between the groups of digits and keep only two decimal places, like this: 25 297 710.10 I tried using the following code snippet: $(td).text().reverse().replace(/((?:\d{2})&bso ...