Trigger in Firebase returns a different node key when making an update request

Examining my database structure, I am aiming to create a Firebase trigger that will update the RoundScore for a specific PlayerID whenever any section of the '/SCORES' node is modified.

"SCORES" : {
       "2017" : {
         "Round_1" : {
           "3" : {
             "Emoji" : "",
             "PlayerName" : "Person A",
             "RoundScore" : 100
               },
           },
       },
   },

"SELECTIONS" : {
    "2015" : {
      "Round_1" : {
        "TEAM A" : {
          "18" : {
            "emoji" : " ",
            "playerName" : "Person A",
            "position" : "POS"
          },
          "19" : {
            "emoji" : " ",
            "playerName" : "Person B",
            "position" : "POS"
          }
     },
        // more team data...
      }
    }
}

The desired outcome after triggering this change in the database is as follows:

"SCORES" : {
        "2017" : {
          "Round_1" : {
            "3" : {
              "Emoji" : "", <------------ DUPLICATE FROM HERE
              "PlayerName" : "Person A",
              "RoundScore" : 100 <------------ AND HERE
                },
            },
        },
    },

    "SELECTIONS" : {
        "2015" : {
          "Round_1" : {
            "TEAM A" : {
              "3" : {
                "emoji" : "", <------------ INSERT HERE
                "playerName" : "Person A",
                "position" : "POS"
                "RoundScore" : 100 <------------ AND HERE
              },
            },
        },
    }

Currently, my implementation only functions with a hardcoded teamID (TEAM A in the provided example).

exports.whenScoresUpdate = functions.database
    .ref('/SCORES/{yearId}/{roundId}/{playerId}')
    .onCreate((snap, context) => {  
        const newScoreData = snap.val();
        const yearId = context.params.yearId;
        const roundId = context.params.roundId;
        const playerId = context.params.playerId;
        const scoreObj = {
            "RoundScore" : newScoreData.RoundScore,
            "Emoji" : newScoreData.Emoji,
        }; 
    return admin.database().ref('/SELECTIONS/' + yearId + '/' + roundId + '/{teamId}/' + playerId).update(scoreObj);

Answer №1

Just a little bit more tweaking and you're there! Have a look at the revised code snippet below for some pointers:

  • If you want to trigger an action "when any part of the '/SCORES' node updates", consider using the onUpdate() trigger instead of onCreate(). Remember to access the updated value with change.after.val(); instead of snap.val();
  • Make sure to correctly define the teamId variable in your code. The expression '
    ...roundId + '/{teamId}/' + playerId....
    ' might not give you the desired results;
  • Handle any potential errors from the update() function by catching possible Promise.reject instances;

    exports.whenScoresUpdate = functions.database
      .ref('/SCORES/{yearId}/{roundId}/{playerId}')
      .onUpdate((change, context) => {

        const newScoreData = change.after.val();

        const yearId = context.params.yearId;
        const roundId = context.params.roundId;
        const playerId = context.params.playerId;

        const teamID = "A"; //<- adjust as needed

        const scoreObj = {
            "RoundScore": newScoreData.RoundScore,
            "Emoji": newScoreData.Emoji,
        };

        return admin.database().ref('/SELECTIONS/' + yearId + '/' + roundId + '/' + teamId + '/' + playerId).update(scoreObj)
            .catch(error => {
                console.log(error);
                //...
            });

       });

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 jQuery to add emoticons to a div element

I am currently developing a small chat application and I would like to incorporate emojis into it. My goal is to allow users to click on an emoji, which will then appear in the text area where they type their message. When a user clicks on "select," I want ...

How to tell if one mesh is contained within another in Three.js

Currently, I am experimenting with Three.js and trying to figure out a way to check if one mesh is completely contained within another mesh. I've created a small robot that moves around inside a home box controlled by the player. While I know how to d ...

The specified file ngx-extended-pdf-viewer/assets/pdf.js cannot be found

I have integrated the ngx-extended-pdf-viewer package in my Angular application using npm to enable the display of PDF content. According to the setup instructions, I have added the following configuration in my angular.json file: "assets": [ ...

The occurrence of TypeError in next.js Dropzone stating that (0 , _mantine_core__WEBPACK_IMPORTED_MODULE_0__.rem) is not a function is indicating

I am encountering an issue while trying to render a dropzone component using Next.js and Mantine. For reference, I am following the documentation at . Here is the import statement: import dropzone I am receiving an error message that says: I have inclu ...

Incorporate Material Design Lite and AMP into your Angular 5 project for a sleek

Looking to develop an e-commerce progressive web app using angular 5. Wondering how to incorporate AMP with angular 5 in Google Material Design Lite. If not viable, what are some alternative options worth considering? ...

Having difficulty defining properties within a JavaScript class

Currently, I am trying to set properties within a JavaScript class: class BookingReports extends ReportsInterface{ var categoryID; constructor() { super(); } init(CatID) { this.categoryID=CatID; } } H ...

How can I use MongoDB updateOne to retrieve the newest document instead of the oldest one?

Apologies for the elementary question, but I am determined to make this code function properly. When using the .updateOne() function in node.js to update my mongo database, I leave the parameters blank thinking it would update the most recently added docu ...

multiple executions of mouseup() within a mousedown() event

$("#canvas").on("mousedown", function(e){ var X1 = (e.pageX - this.offsetLeft) - 8; var Y1 = (e.pageY - this.offsetTop) - 8; $("#canvas").on("mouseup",function(e){ var X2 = (e.pageX - this.offsetLeft) - 8; var Y2 = (e.p ...

How can I ensure that my Vue components do not interfere with each other's data when they are

Scenario Consider the following vue component: <template> <div> <slot>{{ title }}</slot> <ul> <li v-for="label in labels" :key="label"> <input type="checkbox ...

Attempting to modify/align JSON data structure

I seem to be struggling with a task that should be straightforward. I am attempting to adjust the structure and variables of a JSON object to fit specific parameters. Here is the current JSON structure I am dealing with: { "name":"BHPhotovideo", ...

Clicking on a date in Vue.js Fullcalendar

My goal is to retrieve a date value from the onDateClick function of fullCalendar using vue.js and then pass this data to a prop that can be stored in my backend via Laravel. However, I am encountering various undefined errors no matter how I approach th ...

The elements in my code are not displaying as expected

This is my jQuery script: $("#options").popup(null, Settings.DialogOptions) .on("onOk", function(){ Settings.SaveSettings( ); Settings.CloseSettings( ); switch(Settings.GetSetting("displayId")){ case "true": $("#nextId").s ...

Revise the final element in the array

How do I access the last item in an array within an instance of a schema? let TrackerSchema = new Schema({ status: String, start_date: { type: Date, default: Date.now }, end_date: { type: Date }, companyId: { type: mongoose.Schema.Types.ObjectId, ...

Is there a way to incorporate vue samples into an independent HTML document?

Striving to broaden my knowledge of Vue, I set out to create a page with tabs inspired by one of the Vue examples available at . However, an obvious error seems to be eluding me, as I encounter a syntax issue on the line import * as Tabs from 'vue-s ...

Obtain the index of a selected option in a Select Tag using Node.js/Express

When you make a POST request with a form in Node.js/Express For example: <select name="selectname"> <option value="value1">Value 1</option> <option value="value2" selected>Value 2</option> <option value="value3"> ...

Guide to creating the shared section of two wheels with CanvasRenderingContext2D

Is it possible to dynamically draw the shared area of two circular shapes using JavaScript and CanvasRenderingContext2D? My ultimate goal is to be able to adjust the size of the shape, ranging from a complete circle to a mere point. The desired outcome is ...

How to Route in Angular 5 and Pass a String as a Parameter in the URL

I am currently working on an Angular project that focuses on geographic system data. The concept is as follows: I have a component with the route: {path: 'home'}. I aim to pass a geojson URL along with this route, making it look like this: {pat ...

What is the best way to create a function that shifts a musical note up or down by one semitone?

Currently developing a guitar tuning tool and facing some hurdles. Striving to create a function that can take a musical note, an octave, and a direction (up or down), then produce a transposed note by a half step based on the traditional piano layout (i. ...

In MUI v5, the Autocomplete default value is not set

When I try to use the defaultValue prop in the Autocomplete component of MUI v5, the value always ends up being undefined. This is a snippet from my code: const vehicles = [ { name: "Toyota", model: "Camry" }, { name: "Ford&qu ...

Troubleshooting: AngularJS - Issues with nested controllers not functioning properly within ng-include

According to the AngularJS documentation (refer to nested controller fragment), I am attempting to implement nested controllers using ng-include Main.html <body id="spaWrapperApp" ng-app="spaWrapperApp"> <div class="container-fluid" id=" ...