Firebase Functions utilizing Realtime Database to update nested child data

Every 10 minutes, a child is created inside my Realtime Database in Firebase through a webservice that sends data via the Rest API. When this data arrives, a function picks it up. The node contains various values, but the important one for further processing is the device identifier "3523EB". Below is the structure of the node's data:

https://i.sstatic.net/Bpy70.png

The 'device' value "3523EB" needs to be used to update a different table by searching for a match in the devices table based on the imei:"3523EB" value present in the child that requires updating. However, the devices table has unknown values for userID and key, making it challenging to locate the specific child.

I attempted to use

ref.orderByChild("imei").equalTo(deviceRef).on("child_added", function(snapshot)
{

https://i.sstatic.net/igc3m.png

The goal is for the device: "3523EB" entry in the sigfox table to locate and update only the child with imei:"3523EB" in the devices table, where the exact {UserId} and {key} are unknown.

Retrieving values from sigfox when accessing the database is not a problem; however, identifying and updating the corresponding child in devices proves to be difficult.

exports.UpdateDeviceData = functions.database.ref('sigfox/{key}/')
.onCreate((snapshot, context) => {
    
  const deviceRef = snapshot.val()['device'];
  const batteryRef = snapshot.val()['battery'];
  const speedRef = snapshot.val()['speed'];
  const temperatureRef = snapshot.val()['temperature'];
  const latitudeRef = snapshot.val()['latitude'];
  const longitudeRef = snapshot.val()['longitude'];
  const timeRef = snapshot.val()['time'];
                    
    const now = new Date().getTime();
    functions.logger.log('Sigfox Data Updated for device: ', deviceRef);


    var db = admin.database();
        var refi = db.ref("devices/");
        refi.once("value", function(snapshot) {
            snapshot.forEach(function(child) {
                var key = child.key;

                snapshot.ref.update({ 
                    battery: batteryRef,
                    speed: speedRef,
                    temperature: temperatureRef,
                    lati: latitudeRef,
                    longi: longitudeRef,
                    updateTime: timeRef })
                    functions.logger.log('Device Key Details: ',child.val());
            })
        });

    return null;
});

Please assist...

Answer №1

After restructuring, the code now runs smoothly:

    var database = admin.database();
        var queryDevice = database.ref('devices/' + deviceReference).orderByChild("imei").equalTo(deviceReference);
        queryDevice.on("child_added", function (snap) {
          snap.ref.update({ 
            battery: batRef,
            speed: spdRef,
            temperature: tempRef,
            latitude: latRef,
            longitude: longRef,
            updatedTime: currentTime})
        });

All credit to Frank van Puffelen for the assistance.

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

Determine the status of a checkbox in Protractor with JavaScript: Checked or Unchecked?

I'm currently facing a challenge while writing an end-to-end Protractor test. I need to verify whether a checkbox is enabled or not, but it doesn't have a 'checked' property. Is there a way in JavaScript to iterate through a list, check ...

Is there a way to transform a string into a legitimate HTML list by utilizing regular expressions?

I am currently developing an application using angularjs. The data I am receiving from the back-end is in the form of an array. I need to transform it into an HTML list (li), but I'm not sure how to accomplish this. Here is the array string I am wor ...

Creating a dialog box that effectively blocks user interaction

Is it possible to implement a blocking dialog box with JavaScript/JQuery/Ajax? I've been working with the JQuery UI dialog box, but using it asynchronously with callback functions has made it more complicated than expected. For example: ans1 = confi ...

How can I implement a for loop in Node.js?

I am currently experiencing an issue with my for loop while attempting to retrieve data from MongoDB and display it in the browser. The problem is that it only iterates through once, resulting in only the first entry being output. Strangely enough, when ...

Error in React-Native: Unable to locate main project file during the build process

Just integrated cocoapods into a React Native project. After a successful build, RN is throwing this error... https://i.stack.imgur.com/czn2W.png No errors in Xcode during the build process, but Xcode is displaying these warnings https://i.stack.imgur.c ...

Struggling with making an Ajax and Jquery drop down menu work? Wondering how to use Javascript to retrieve a variable and then utilize it in PHP? Let's troubleshoot

Currently, I am utilizing Ajax/Jquery to present a dropdown menu with data retrieved from my SQL database. The process involves using javascript to obtain a variable that is then utilized in PHP. However, the function doesn't seem to be working as exp ...

Discovering every element on a webpage

Searching for elements in a webpage can be done using different methods. document.getElementsByTagName('*') and document.all Are there any other more efficient ways or are these two the most recommended? I am currently working on an element se ...

When trying to upload a file using multer, an error occurred stating "Unexpected field

My current issue involves using multer to upload an image from a form. However, I am encountering an Unexpected field error after uploading the image. In my HTML code, I have specified the file and file-model names as myFile. app.js var express = re ...

Creating a dropdown button in HTML table cells with JavaScript: A comprehensive guide

I'm attempting to create a drop-down button for two specific columns in my HTML table, but all the rows are being converted into drop-down buttons. I only want the "categorycode" and "categoryname" columns to be drop-down. $(document).ready(functio ...

Create a function that can accept either no parameters or one parameter depending on the input parameter provided

Do you think there is a more efficient way to write this code? The function Z can be called with either one parameter or with no parameters. If the parameter Y is passed in, then the function z(y) is returned, otherwise just run the function z() async x ...

Implementing Vuejs sorting feature post rendering

Currently, I have elements linked to @click event listeners. <th @click="sort('dateadded')" class="created_at">Date Added I am looking for a way to automatically trigger this sorting function when the Vue.js component renders, so that th ...

Ensuring the validation of JSON schemas with dynamically generated keys using Typescript

I have a directory called 'schemas' that holds various JSON files containing different schemas. For instance, /schemas/banana-schema.json { "$schema": "http://json-schema.org/draft-06/schema", "type": "object", "properties": { "banan ...

What is preventing me from dynamically generating a property?

As someone who is new to TypeScript, I have a question regarding defining properties. In JavaScript, we can define a property dynamically like this: class Rectangle { constructor(height, width) { this.height = height; this.width = width; } } ...

Failed to fetch http://localhost:8000/Stack/script.js due to network error 404 in Django project

As I embark on creating a simple to-do app, I encountered an error while trying to implement some JavaScript on the homepage. The error in question is highlighted above (Get http://localhost:8000/Stack/script.js net:: Err_Aborted 404). Being new to integra ...

What are the steps to import a .obj 3D model into Three.js?

After incorporating your advice, here is the revised code: var renderer = new THREE.WebGLRenderer( { alpha: true } ); renderer.setSize( window.innerWidth, window.innerHeight ); element.appendChild( renderer.domElement ); var loader = new THREE.OBJLoader( ...

What is the best way to import the axios post method from a JavaScript file into a Vue component

I'm encountering an issue when trying to export the data received from the API in my JavaScript file and display it in my Vue file. Currently, I am sending a security JSON to the server using the POST method. Although I am able to retrieve the output ...

Encasing common functions within (function($){ }(jQuery) can help to modularize and prevent

As I was creating a global JavaScript function and made some errors along the way, I finally got it to work after doing some research. However, while searching, I came across an example using (function($){ code here }(jQuery); My question is, what exact ...

Using Jquery to toggle the visibility of div elements with the same structure, but ensuring only one is

Many people have posed this question. I am attempting to create a functionality where a div can expand and collapse using a +/- button. I have 5 divs with class=="expanderContent". When the function below is triggered by a click, all 5 items expand or coll ...

best way to eliminate empty strings from an array collection using javascript

I'm currently working on a search functionality where I separate each value in an array, and it's functioning properly. The issue arises when the user enters an empty value, causing the search to break as it returns an empty string within the arr ...

How to choose `optgroup` in Vue 1.x

In previous iterations of vue.js, developers had the ability to generate a dynamic select list utilizing optgroups similar to the example found here. In the latest versions of vue, the documentation suggests using v-for within the options instead of optgr ...