Is your Cloud Functions task generating an Array when querying?

To access items and products in my database, I need to retrieve the "ean" field from the product and check if it matches the one in the request body.

The structure of my database is as follows:

"cart": {
  "items": {
    "0": {info here},
    "1": {info here}
    "2": {
      "more info here",
      "product": {
         "available": true"
         "quantity": 231,
         "ean": "0000001312"
      }
    continue listing until 47

However, when I run my cloud function:

exports.getItemByEan = functions.https.onRequest(async (request, response) => {
  const db = admin.database();
  const items = db.ref();
  const eanRef = items.child('cart').child('items');
  const query = eanRef.orderByKey();

  try {
    const dataSnapshot = await eanRef.once('value');
    response.send(dataSnapshot.val());
  } catch (error) {
    console.log(error)
  }
  }) 

});

I'm having trouble retrieving the specific product by its Ean code. The result seems to be an array instead of an object, and the keys aren't appearing as expected:

[
    {,
        "product": {
            "available": true,
            "quantity": 9183
            "ean": "0000000000017",
    },
    {

   "product": {
            "available": true,
            "quantity": 131
            "ean": "0000000044790",
        },
    },
    .....continues

I want to understand why the query result is an array instead of an object with keys like in the Firebase Database. Additionally, I'm looking for a better way to find a specific product by its Ean code.

For example, when I try:

const db = admin.database();
const items = db.ref();
const eanRef = items.child('cart').child('items').child('product'); // This doesn't work, it returns nothing. Why? Isn't the "product" field inside the item?

Answer №1

In cases where the database keys are exclusively numeric, the data structure returned will be an array rather than an object. The elements within the array will correspond directly to the keys of the nodes in the database. It is essential for your code to account for this situation and handle it accordingly. If you require the client to receive an object instead of an array, you must perform the conversion manually.

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

Adjust the scope variable upon submission and refresh the display in AngularJS

Currently, I am working on my first web app using angularjs and facing an issue where the page does not update with new values once the user submits text or numbers in an input box. For this project, I am utilizing Java8, MongoDB, angularJS, and twitter b ...

Requesting AJAX page yields a null $_GET parameter

Content loaded dynamically via AJAX methods. The base page is index.php, and profile.php is the page that gets loaded. The jQuery code snippet below has nothing to do with an HTML request: $('<a/>', {href: '?userID='+post[' ...

Practice window.performance.getEntriesByType with a mock function

I am facing an issue in my component where I need to check if the page is reloaded and redirect to another page. Here is the code snippet I am using: useEffect(() => { //this will prevent users from accidentally refreshing / closing tab window.o ...

Is jQuery .ajax not able to make CORS request while Native XMLHttpRequest() successfully does?

When I use the vanilla XMLHttpRequest() object to make a CORS request, it works perfectly fine. However, when I try using the jQuery.get() function, it tells me that cross-origin requests are not allowed. This is confusing because $.get() is built on top o ...

Zoom out the slider when scrolling

Take a look at this link and as you scroll down the page, notice how the image transitions to iPhone. Can anyone provide insight on how this effect is achieved? ...

Encountering an issue with Server Side Rendering in React Router Dom where an error message pops up saying: "Warning: React.createElement: type is

Specific Error: A warning has occurred: React.createElement: the type provided is invalid -- it was expecting a string (for built-in components) or a class/function (for composite components), but instead received an object. in Posts in Connect(Po ...

What is the best way to handle mapping an array with uncertain levels of nesting?

My task involves rendering an array of comments in ReactJs, each of which can have nested comments at unknown levels. I am struggling to figure out how to display these comments with their respective nesting levels. comment 1 -- comment 2 -- comment 3 --- ...

Having trouble with my ReactJS application where click interactions are functioning properly on the header but not on my content

Objective: Implement an iframe displaying a YouTube video with play/pause functionality for users. Issue: Unable to interact with main content, but works correctly when placed in Navigation or Footer components. Attempted Solutions: Explored various de ...

Rails - implementing ajax in partials causing an error: 'cannot find method render'

I am encountering an issue with my form partial located within a div that has the id "chapcomments". The form includes a submit button: <%= f.submit "Post", remote: true %> Within the correct view folder, I have a file named create.js.erb which con ...

Is it possible to exchange code among several scripted Grafana dashboards?

I have developed a few customized dashboards for Grafana using scripts. Now, I am working on a new one and realizing that I have been duplicating utility functions across scripts. I believe it would be more efficient to follow proper programming practices ...

Discover the pixel width of a Bootstrap grid row or container using JavaScript

How can I calculate the width of a Bootstrap grid row or container in pixels using JavaScript? I am working with Aurelia for my JavaScript project, but I'm open to solutions in standard JS (no jQuery, please). Looking at the Bootstrap documentation, ...

Can you guide me on implementing AWS SDK interfaces in TypeScript?

Attempting to create an SES TypeScript client using AWS definitions file downloaded from this link My approach so far: /// <reference path="../typings/aws-sdk.d.ts" /> var AWS = require('aws-sdk'); var ses:SES = new AWS.SES(); The error ...

Obtaining the width of a scrollbar using JavaScript in the most recent version of Chrome

Looking for a way to determine the width of the scrollbar using JavaScript for CSS purposes. I attempted the following: document.documentElement.style.setProperty('--scrollbar-width', (document.offsetWidth - document.clientWidth) + "px" ...

I am encountering problems with images that are imported as module imports in a Vue.js project

Currently, I have stored all the default images for my Vue project in a designated folder. The path to this folder is web/images/defaults/<imageNames>.png. Instead of importing each image individually in my components, I wish to create a file that co ...

Is it considered inefficient to import every single one of my web components using separate <script> tags?

Currently, I am in the process of developing a website with Express + EJS where server-side rendering is crucial. To achieve this, I am utilizing web components without shadow dom. Each page type (home, post, page) has its own EJS view. For instance, when ...

Why does the Hamburger Menu shift my website's logo when it opens?

I'm in the process of implementing a hamburger menu on my website. My attempts have involved adjusting the positioning of both the #logo and .topnav elements. Code Snippet source function myFunction() { var x = document.getElementById("myTopn ...

When the function is executed, the error message "obtaining ID

As I attempt to remove items from a group and automatically delete the group if there are no items left, I encounter an error in Vue indicating that 'id' is not defined. This seems puzzling to me because it should have already completed the opera ...

Refreshable div element in a Code Igniter-powered web application

I am encountering difficulties with automatically refreshing my div using the CodeIgniter framework. My goal in the code snippet below is to have the particular div with id="lot_info" refresh every 1 second. The div is not refreshing, and an error message ...

Determine in Node.js whether an image is empty or not

I am in the process of developing a testing application that generates an image based on the URL provided by the user. The screenshots are captured using phantomJS and nightmareJS. Occasionally, users may input a non-existent URL, resulting in a blank ima ...

Developing a webpage that navigates seamlessly without the hassle of constantly refreshing with

I am in the process of creating a website that is designed to run everything within the same file, but I am unsure about how to locate study materials for this project. For example: In a typical website scenario -> If I am on index.php and I click on ...