Guide on accessing a node within the firebase database

My goal is to allow each user to choose a total of 6 players. When a player is selected, their player ID is sent to a node on the database called 'total' using the push() method. The code snippet is provided below:


var ref = firebase.database().ref().child('players');

var ref3 = firebase.database().ref().child('users').child(uid).child('total');

$scope.players = $firebaseArray(ref);

console.log($scope.players); 

$scope.history = [];

$scope.buy = function(player) {
    // Remove if already added locally
    var index = $scope.history.indexOf(player);
    if(index >= 0){
        $scope.history.splice(index,1);
        return;
    }

    // Remove if already added on firebase

    // Max of 6 players allowed
    if($scope.history.length >= 6){
        alert('Max of 6 players allowed');
        return;
    }

    var selected = $scope.history.reduce(function(a,b){
        a[b.position] = (a[b.position] || 0) + 1;
        return a;
    }, {}) || {};

    if(!selected[player.position] || selected[player.position] < 2){
        $scope.history.push(player);
        ref3.push(player.id);
    }else{
        alert('You can only add two players per position');
    }
};

$scope.getTotal = function(){
    return $scope.history.reduce(function(tot, p){
        tot = tot - p.price;
        return tot;
    }, $scope.total);
};    

This is the current structure of the database:


{
   "players" : [ {
      "R" : 0,
      "Team" : "Industry",
      "Y" : 0,
      "assists" : 0,
       ...
     }],
    "users" : {
        "l3J1TVsFNLMi0Oxg6hz4AJpacE53" : {
            "email" : "example@email.com",
            "fullname" : "Djflex11",
            "teamname" : "deji awoniyi",
             ...
          }
     }
}

My Challenge

The issue I'm facing is ensuring that a player cannot be selected twice by the same user. Currently, my code prevents a player from being selected twice locally, but allows the same player ID to be pushed to the Firebase database. My challenge is figuring out how to check the 'total' node so that if a selected player is already in the database, it will be removed instead of inserted again. I am aware that 'indexOf' should be avoided with Firebase.

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

Encountering additional characters when employing multiple optional parameters in an Angular route

I've been working on a project using angularjs router, and since I'm almost finished with the development, UI-router isn't an option for me. Recently, I added two optional parameters to a route by following this answer. Here is what I implem ...

Using Angular to Access External Services with Self-Signed Certificates

Is there a way to interact with external self-signed HTTPS services in Angular by either passing or attaching the certificate used by the service? I'm not too familiar with Angular, but I know that it's possible in the cURL library to attach a si ...

I'm looking for a way to incorporate JavaScript code within an iframe tag. Specifically, I'm attempting to embed code into a Wix website using the "Embed HTML

Trying to execute the code below on a Wix website using "Embed HTML", but IFRAME is blocking scripts. Seeking help to embed custom HTML with JavaScript on platforms like Wix.com or Wordpress.com, as the embedded code is not functioning due to IFRAME restri ...

What steps can I take to resolve my password validation rule when confirming during sign-up?

Utilizing react-hook-form in combination with Material-UI for my sign-up form has been a challenge. I am currently working on implementing a second password field to confirm and validate that the user accurately entered their password in the initial field, ...

Persistent button positioned at the bottom of the page, remaining visible even when scrolling to the very end of the content

I am looking to add a floating button that remains in the same position relative to the content until the window is scrolled to a certain point, after which it sticks to the end of the content. In simple terms, I want the element to act as 'relative& ...

What is preventing me from binding the array index to a model in AngularJS with two-way binding?

I'm currently facing a challenge with a seemingly simple task: I have an array of string values that I want to link to a select element's options, and then connect the index of the chosen value to a variable. However, I have found that neither us ...

Troubleshooting problems with production builds in Angular 5 using Node.js Express

Encountered a problem while attempting to create a production build of my angular and node.js project. Running the angular project with ng serve and backend with nodemon server works fine. However, after running ng build --prod and modifying the backend to ...

Reactjs rendering problem related to webpack

Greetings! I am new to using react js and decided to create a quiz application. However, I encountered an error when the render function was called. Below is my webpack.config file: module.exports = { entry: { app: './src/index.js' }, ...

The previous button on Owl Carousel seems to be malfunctioning after navigating from a different page

In my case, I have two distinct pages: let's call them the first and second pages. On the first page, I utilize an owl carousel slider with a tag that links to a specific slide on the second page's owl carousel slider using an ID. Meanwhile, on ...

Having difficulty in compressing Vue.js application

My Vue.js Application contains the following code snippet: (function() { initApp(); })(); function initApp() { window.myApp = new Vue({ el: '#wrapper', data() { return { somedata: [] } } }); } & ...

Is the Integer Division in Javascript the same as Math.floor(x) for x greater than or equal to 0, or is x | 0 equivalent?

After examining the examples below, it appears that Math.floor(x) is the same as x | 0 when x >= 0. Is this accurate? And if so, why is that the case? (or how is x | 0 computed?) x = -2.9; console.log(Math.floor(x) + ", " + (x | 0)); // -3, -2 x = -2 ...

What is the solution for resolving the error message "handling locally caught exception"?

When dealing with a REST API call, the function responsible for handling it may encounter situations where various functions called to process parts of the request throw errors indicating that an error code should be returned as a response. Additionally, t ...

Finding the index of a column based on a continuous sequence of values can be achieved by following these

Consider this sequence of numbers representing components on a page: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 Every set of 3 numbers makes up a page, with indexing restarting for each new page. Essentially, it follo ...

Learn the process of applying distinct CSS classes to various elements within an AJAX response

The client initiates an AJAX call via jQuery. Upon fetching data from the database, I return the response which includes the application of numerous classes and styles to various HTML tags. Unfortunately, this process results in code that appears unsightly ...

Calculating the total sum of values within a JSON array

Here is the data that I am working with: input1 = [{ "201609": 5, "201610": 7, "201611": 9, "201612": 10, "FY17": 24, "metric": "metric1", "careerLevelGroups": [{ "201609": 3, "201610": 6, "201611": ...

Can the minDate and maxDate be set for the same day in the Tempus Dominus Bootstrap 4 datetimepicker?

I've integrated the TempusDominus Bootstrap4 DateTime Picker into my project, which can be found at . I have two simple input fields in HTML, defined as follows: <div class='mb-3'> <input type="text" class="form-control dateti ...

Hidden Password Field Option in HTML

My HTML password textbox has the input type set as password, but I can still see what is being typed. This shouldn't happen as password inputs should be masked. Can someone please advise me on how to resolve this issue? To replicate, copy the code be ...

Integrate ng-admin with ui-router for enhanced functionality

My AngularJS project (version 1.4.9) is built using ui-router and contains multiple states defined as follows: .state('overview', { url: '/overview', parent: 'dashboard', templateUrl: 'views/dashboard/overview.html ...

Generate a new tree structure using the identifiers of list items within an unorganized list

Attempting to convert the id's of li's in a nested unordered list into valid JSON. For example, consider the following list. To be clear, the goal is not to create the UL list itself, but rather the JSON from the li id's <ul class="lis ...

What are the steps for combining AngularJS with Java JAAS authentication system?

My web application combines AngularJS on the frontend with Java on the backend. Angular communicates with the Java backend through Restful webservices exchanging JSON data over HTTP. I am in need of developing an authentication mechanism for this app and I ...