Querying Firebase's real-time database for specific sub-child data

Here is the structure of my database: https://i.sstatic.net/Tduqg.png

I have successfully retrieved all the documents by querying the userId:

this.orderListRef = firebase.database().ref(`/orderList`);
this.orderListRef.orderByChild('userId').equalTo(`${this.currentUser.uid}`)

However, I am facing difficulty in retrieving all the documents by querying the sub key restId in the order array. The codes I tried returned null:

this.orderListRef.orderByChild('order/restId').equalTo('-L6vQHDBv9WugS_yTibn').on('value', snap => {
      console.log(snap.val())
    })

and

this.orderListRef.child('order').orderByChild('restId').equalTo('-L6vQHDBv9WugS_yTibn').on('value', snap => {
  console.log(snap.val())
})

Any help would be greatly appreciated. I want to receive a result that contains "-L6vQHDBv9WugS_yTibn" in the restId key only, like:

-L9IZKHkueFppGMJY3Z9: {deliveryAddress: "Kuala Lumpur, Federal Territory of Kuala Lumpur, Malaysia", dtcreate: 1522894198149, order: Array(2), userId: "AeMgnwHy3Hav3FE9DyTMJVdp4QX2", userOrderNumber: "pGMJY3Z9"}
-L9I_DcXgx_fjsmsn2rm: {deliveryAddress: "Kuala Lumpur, Federal Territory of Kuala Lumpur, Malaysia", dtcreate: 1522894433661, order: Array(2), userId: "AeMgnwHy3Hav3FE9DyTMJVdp4QX2", userOrderNumber: "jsmsn2rm"}
-L9IksHXG4WZo0ejfmk1: {deliveryAddress: "Kuala Lumpur, Federal Territory of Kuala Lumpur, Malaysia", dtcreate: 1522897487221, order: Array(2), userId: "AeMgnwHy3Hav3FE9DyTMJVdp4QX2", userOrderNumber: "o0ejfmk1"}

Thank you in advance!

Edited 1: Following Frank van Puffelen's suggestion to create restaurant as a child of the orderList ID, I found it to be a good idea but unfortunately, it didn't work.

Here is the updated screenshot of my database: https://i.sstatic.net/Id3kD.png

I have tried the queries below but all of them still return null:

this.orderListRef.orderByChild('restaurant').equalTo('rest001').once('value', snap => {
      console.log(snap.val())
    })

this.orderListRef.child('restaurant/rest001').once('value', snap => {
      console.log(snap.val())
    })
this.orderListRef.child('restaurant').equalTo('rest001').once('value', snap => {
      console.log(snap.val())
    })

this.orderListRef.child('restaurant').orderByChild('rest001').once('value', snap => {
      console.log(snap.val())
    })

Thank you for your assistance!

Answer №1

The field order/restId does not exist. However, there are fields order/0/restId and order/1/restId, but querying on them is not possible due to the dynamic path.

Your current data structure is effective for finding restaurant IDs for a given order, but not for finding orders for a specific restaurant ID. To enable this functionality, you should enhance your data structure to include inverted data:

restaurants
  restaurantId1
    order1: true
    order3: true
  restaurantId2
    order2: true

With this update, you can easily retrieve orders for a particular restaurant by accessing them under /restaurants/$restaurantId.

For further insights, refer to:

  • Firebase query if child of child contains a value
  • Firebase Query Double Nested

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

The method for retrieving values and $id from a $firebaseArray using angularJS

Hey there, I'm fairly new to working with Firebase and I seem to be stuck on a problem that I can't find a solution for despite looking in many different places. Here is the structure of my Firebase database: I am trying to retrieve data from a s ...

npm ERROR! The requested resource at http://registry.npmjs.org/amcharts4 could not be located - Error 404: Resource Not Found

I'm running into an issue while trying to include npm package dependencies in my Angular project. Can anyone assist me in resolving this error? C:\Users\TM161\Desktop\Master\stage PFE\SNRT-Music>npm i npm ERR! code ...

The Angular Universal error arises due to a ReferenceError which indicates that the MouseEvent is not

I am encountering an error while trying to utilize Angular Universal for server-side rendering with the command npm run build:ssr && npm run serve:ssr. This is being done in Angular8. /home/xyz/projects/my-app/dist/server/main.js:139925 Object(tslib__WEB ...

TypeScript/Javascript - Error: The specified function is not callable

After recently delving into TypeScript, I found myself encountering an error in my code for a wheel mini-game on my app. The specific error being displayed in the console is: this.easeOut is not a function The relevant portion of the code causing the iss ...

The error message TS2339 in Angular service.component indicates that the property 'subscribe' is not recognized on the type 'Promise<Object>'

Currently, I am in the process of learning Angular by developing a web application for my parish. I have implemented a method for deleting items in the products-list.component.ts file which appears to be technically correct. However, when I attempt to run ...

Having trouble with VS Code on my Linux system - npm error popping up?

protons@protons-HP-EliteBook-840-G3:~/Desktop/NH_Facility_Portal_V0$ sudo npm install [sudo] password for protons: npm notice npm notice New minor version of npm available! 8.12.1 -> 8.13.2 npm notice Changelog: https://github.com/npm/cli/releases/tag ...

Synchronize information between mongoDB and firebase bidirectionally

My current situation: Having developed an application using React, NodeJS, and Electron, most of my users utilize the app offline. Next plans: With intentions to cater to mobile users as well, I am considering creating a mobile application using React-N ...

Effectively enhance constructor by incorporating decorators

Is it possible to properly extend a class constructor with decorators while maintaining the original class name and static attributes and methods? Upon reading the handbook, there is a note that cautions about this scenario: https://www.typescriptlang.or ...

When attempting to access the Angular app in Edge, it automatically redirects to open in IE 11 instead

I have encountered an issue with my angular 5 App. It works perfectly fine in Chrome and Firefox, but when I try to open it in Microsoft Edge on Windows 10, the application always opens in the IE 11 browser. There are no errors displayed on the console. W ...

Angular: Utilize a Pipe in Template to Format and Display Time With a Mask

Within my code, there's a function called secondsToHms that serves to convert seconds into hours, minutes, and seconds: transform(seconds: number): string { const minutes = Math.floor(seconds / 60); //minutes const secs = seconds % 60; //seconds ...

What is the solution for resolving the error related to converting implicit any type to index type in TypeScript?

Can you help with fixing this issue? "How do I resolve the error: 'Element implicitly has an 'any' type because expression of type 'any' can't be used to index type?' " What could be causing this problem? Can you expla ...

Does Apollo Federation provide support for a code-first development approach?

I have declarations using 'code-first' approach in my project, but now I want to utilize them as microservices. How can I separate my 'typeDefs' and 'resolvers' following Apollo's 'schema-first' methodology? Is ...

Angular 2, using Jasmine and Karma for testing, encountered an error with the HTTP testing API, which returned an error message stating: {"isTr

I've set up an http test case for my Angular2 app using Jasmine-Karma and encountered an API error: Uncaught API Error. Scenario: I'm trying to test an http service for my Angular2 App using Karma-Jasmine, and I've implemented the method be ...

Issue with NGRX: component does not reflect state changes

Whenever I click on a button, it is supposed to open up a Google map. Upon clicking, I can see Google scripts being inserted, which triggers a callback that sends a message to my reducer. After receiving the message, I can confirm through logging that the ...

Using jest, assess the functionality of a service and observe its behavior

I recently made the switch from using Jasmine to Jest for my Angular unit tests. I made updates to the spec code to test a service, like so: .... describe( 'My Test', () => { let myService: any; ... beforeEach(() => { my ...

Tips for decreasing the size of your Angular 7 production build

What are the best practices to minimize production build size? For production build, use the command ng build --prod To configure angular.json file, refer to the following links: https://i.stack.imgur.com/3LSxZ.jpg https://i.stack.imgur.com/yE0fL.jpg ...

The error message displayed in the Typescript Playground is stating that there is no property named 'values' on the type 'ObjectConstructor'

Could someone please take a look at this link? I'm encountering an error with the playground and I'm not sure why. Click here ...

The use of throwError(error) has been phased out, however, no replacement has been introduced for the Error(HttpErrorResponse)

It seems like the use of throwError(error) is deprecated now. VS Code suggests using throwError(() => new Error('error')) instead, as new Error(...) only accepts strings. How can I replace it correctly without causing issues with my HttpErrorH ...

The distinction between <Type>function and function name():Type in TypeScript is essential to understand the various ways

function retrieveCounter(): Counter { let counter = <Counter>function (start: number) { }; counter.interval = 123; return counter; } Upon inspection of line 2 in the code snippet above, I am left wondering why I am unable to use function ...

reinstate dummy of external class method in ts-jest

Problem I am encountering an issue while trying to mock a function that is imported from another class and called within the main class. Although I can successfully mock the function and return the specified values, I am unable to revert the mocked functi ...