Having trouble processing the Firebase snapshot with Node.js

I have a question regarding a snapshot;

ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {})

After printing the snapshot with ;

console.log(snapshot.val());

This is the output that gets printed;

{'-LBHEpgffPTQnxWIT4DI':
    {
        date: '16.05.2018',
        first: 'let me in',
        index: 1,
        second: 'let others in'
    }
},

I am trying to extract the values of date and the first value from this snapshot.

I attempted to access them using;

childSnapshot.val()["first"] 
childSnapshot.val()["date"] 

or

childSnapshot.child.('first') 
childSnapshot.child.('date') 

but unfortunately, it did not work as expected.

Please point out the mistake I might be making...

The complete code snippet is provided below;

var indexRef = db.ref("/LastIndex/");
var ref = db.ref("/Source/")

indexRef.on("value", function(indexSnapshot) {
    console.log(indexSnapshot.val());

    var currentIndex = indexSnapshot.val()

    ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {
        console.log(snapshot.val());

        if(snapshot !== null) {
            snapshot.forEach(function (childSnapshot) {

            if(childSnapshot !== null) {
                var newRef = db.ref("/ListTest/");
                var key = newRef.push({
                    "firstLanguageWord": childSnapshot.val()["first"] ,
                    "secondLanguageWord": childSnapshot.val()["second"] ,
                    "wordType": childSnapshot.val()["type"],
                    "date": childSnapshot.val()["date"],
                    "translateType": childSnapshot.val()["transType"]
                });

                currentIndex++;
                indexRef.set(currentIndex);
            }
        });
    }
});

Best regards,

Erdem

Answer №1

Based on your feedback and the updated original question:

If it seems like your code is stuck in an infinite loop, it could be due to using the on() method with your initial query. The on() method actually "listens for data changes at a particular location," as described here.

If you only need to query the reference once, consider using the once() method instead. More details are available here.


This snippet represents a Query, since you're utilizing the orderByChild() method on a Reference (along with an equalTo() method).

ref.orderByChild("index").equalTo(currentIndex)

As explained here in the documentation:

Even when there is only a single match for the query, the snapshot is still considered as a list; albeit containing just one item. To access that item, iterating over the result is necessary:

ref.once('value', function(snapshot) {  
  snapshot.forEach(function(childSnapshot) {
    var childKey = childSnapshot.key;
    var childData = childSnapshot.val();
    // ...   
   }); 
});

Hence, the correct approach would be:

ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {
     snapshot.forEach(function(childSnapshot) {
        console.log(childSnapshot.val().first);
        console.log(childSnapshot.val().date);      
       }); 
});

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

How to use jQuery Animate to create a step-by-step animation with image sprites?

I'm working on creating an image sprite using jQuery and I'm curious if it's feasible to animate it in steps rather than a linear motion. I initially tried using CSS3 animations, but since IE9 is a requirement, the animations didn't wor ...

What are the steps to checking login functionality utilizing the Facebook and Google APIs?

I am currently utilizing the express framework, along with chai for testing purposes. When it comes to local login, I have been testing by passing data such as {mobile_number, otp}. Depending on the response received, the test either passes or fails ...

Add information to the Database seamlessly without the need to refresh the page using PHP in combination with JQuery

Check out my code below: <form action='insert.php' method='post' id='myform'> <input type='hidden' name='tmdb_id'/> <button id='insert'>Insert</button> <p i ...

What is the best way to integrate my custom JavaScript code into my WordPress theme, specifically Understrap?

I am looking to enhance my website with a sticky navbar positioned directly under the header, and I want it to stick to the top of the page as users scroll down. Additionally, I want the header to disappear smoothly as the user scrolls towards the navbar. ...

Leveraging ng-click and ng-hide/show directives within ng-repeat in Angular

I have a simple Single Page Website built with Angular. I utilized ng-repeat to generate content on the main page, where each item is an image. I am looking to create an alternate view for each image to display more details. I have implemented this feature ...

Placing a div over a JavaScript element

Is it feasible to overlay a div(1) with a background image on top of another div(2) that contains JavaScript (like Google maps API v3)? I have experimented with z-index without success, and I am unable to utilize absolute positioning because I depend on t ...

Node.js POST Request Batch Processing

For my request, I need to send a batch of 40 items with a 10-second break between each batch. After updating the parameters, when I run the following code: const request = require('request'); let options = { 'method': 'POST' ...

Maintaining Scene Integrity in THREE.JS: Tips for Handling Window Resizing

My layout includes a div with a scene that looks great initially; however, as soon as I start moving or resizing the window, the scene overflows the boundaries of the div and goes haywire, almost filling the entire window. Are there any techniques or solu ...

Is there a way for me to extract and showcase the initial 10 items bearing a particular class name from a different html document on my homepage?

I am looking to extract a list of movies from an HTML file titled "movies.html". The structure of the file is as follows: <div class="movie">Content 1</div> <div class="movie">Content 2</div> <div class=" ...

What is the best way to add JSON data to a table?

I have developed a php script to create json data. However, I am facing an issue while trying to display this generated json data in a table. While my php code successfully generates the data, it is unable to insert it into the table. I would appreciate an ...

Error: FileReader is not defined in Node.js (Nest.js) environment

I am working on converting my image to base64 using a custom function. However, when I try to execute the code, I encounter an error message stating ReferenceError: FileReader is not defined. This error has left me puzzled and unsure of its cause. Below i ...

Having trouble making JSON work alongside Ajax and jQuery?

In my JavaScript, I have the following code snippet... $.ajax({ type: 'POST', url: 'http://www.example.com/ajax', data: {email: val}, success: function(response) { alert(response); } }); The PHP fil ...

Having trouble with enter key input not triggering?

I have scoured various resources for answers to my query, including Stackoverflow. Unfortunately, none of the posts I came across have helped me resolve my issue with getting the enter key to work in my project for FreeCodeCamp on Codepen. When I press the ...

In JavaScript, the code is designed to recognize and return one specific file type for a group of files that have similar formats (such as 'mp4' or 'm4v' being recognized as 'MOV')

I am working on a populateTable function where I want to merge different file types read from a JSON file into one display type. Specifically, I am trying to combine mp4 and m4v files into MOV format. However, despite not encountering any errors in my code ...

Modifying the src attribute of an object tag on click: A step-by

So I have an embedded video that I want to dynamically change when clicked on. However, my attempt at doing this using JavaScript doesn't seem to be working. <object id ="video" data="immagini/trailer.png" onclick="trailer()"></object> H ...

Discover the power of lodash's .groupBy method as you learn how to efficiently group objects within another

Utilizing lodash's _.groupBy function, I have generated the following data: { "Generic Drugs":[ { itemDes: "Dulcolax", itemGeneric: "Bisacodyl", pr ...

What is the resolution process for importing @angular/core/testing in TypeScript and what is the packaging structure of the Angular core framework?

When using import {Injectable} from '@angular/core';, does the module attribute in package.json point to a file that exports injectable? Also, for the format @angular/core/testing, is there a testing folder within @angular/core that contains anot ...

Iterate through the xml.documentElement in a loop

I want to show 8 men and 2 women in SVG format. However, my current function only displays one man and woman. How can I add a loop to make this work for all individuals? for (i = 0; i < Serie[n].Number; i++) { return xml.documentElement } The data arr ...

Validation of JSON Failed

Encountered a 400 Bad Request error while attempting to POST an answer using Postman, it appears to be a validator issue. Despite multiple attempts, I have yet to resolve this issue. Below are details of the JSON data being sent in the POST request along w ...

Delivering a protected, locally hosted NextJS project with numerous subdomains

In the configuration of NextJS' server.js, you can ensure secure self-hosted server by including: https.createServer({ key: fs.readFileSync('./privkey.pem'), cert: fs.readFileSync('./cert.pem'), ca: fs.readFileSync('./ch ...