Firestore orderBy does not retrieve any documents, resulting in 0 results

I'm having an issue with my orderBy query. Here's what it looks like:

  async list() {
    const snapshot = await this.firestore
      .collection("queue")
      .orderBy(`ignoreUserIds.Po0fouROHVQnrV1ZR17L8Tql3OJ2`)
      .limit(10)
      .get();
    return snapshot.docs.map((e) => e.data());
  }

Despite there being documents in the collection, when I run the query, it returns 0 documents.

The document has a different userId in the map. However, I believe that should not impact the result as orderBy is supposed to just order the documents, right?

I've also created an index for this query:

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

This is how the documents look like:

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

I am looking to retrieve all documents while ordering them based on a specific field.

Answer №1

However, upon running it, the result is 0 documents

This outcome was expected since there is no key "Po0fouROHVQnrV1ZR17L8Tql3OJ2" present in the "ignoreUserIds" Map.

The document contains a different userId in the map.

This is why you are not receiving any documents.

But doesn't that detail shouldn't affect the results?

Actually, it does matter.

Will orderBy fetch all documents and sort them accordingly?

No, because you are attempting to sort based on a field that does not exist.

I just want to retrieve all the documents but sorted by the specified field

In order to achieve this, you must use the exact UID (aKWp...VNo2) that is stored in the database.

Additionally, consider using either not equal (!=) or not-in if it better fits your requirements.

Answer №2

A orderBy() statement has a restriction in that it also serves as a filter for the presence of the specified field. Any documents lacking the given field will be excluded from the result set.

For instance, let's consider a Firestore collection named users with 3 documents - user1, user2, and user3. Each document includes a field called ignoreUserIds of type Map, containing values like id : 4, id2 : 2, and id3 : 5 for user1, user2, and user3 respectively.

users----->
    user1---->
        ignoreUserIds : 
                id : 4
    user2---->
        ignoreUserIds : 
                id2 : 2
    user3---->
        ignoreUserIds : 
                id3 : 5

The queries below will yield their respective outcomes:

db.collection("users").orderBy('ignoreUserIds.id').get() => only user1
db.collection("users").orderBy('ignoreUserIds.id2').get() => only user2 
db.collection("users").orderBy('ignoreUserIds.id3').get() => only user3 
db.collection("users").orderBy('ignoreUserIds.id4').get() => 0 documents //since there are no documents inside 'users' collection with the field 'ignoreUserIds.id4'.

In your situation, it appears that the field referenced in the orderBy() statement,

ignoreUserIds.Po0fouROHVQnrV1ZR17L8Tql3OJ2
, is not present in any documents within the queue collection. Hence, you're receiving 0 documents.

Furthermore, if you intend to sort the documents based on userIds found within the ignoreUserIds field, I recommend specifying just ignoreUserIds in the orderBy clause to achieve this sorting.

Your query should resemble the following -

const snapshot = await this.firestore
      .collection("queue")
      .orderBy(‘ignoreUserIds’)
      .limit(10)
      .get();

You can explore this documentation for more insights into the orderBy() statement and its limitations.

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 can you display or list the props of a React component alongside its documentation on the same page using TypeDoc?

/** * Definition of properties for the Component */ export interface ComponentProps { /** * Name of something */ name: string, /** * Action that occurs when component is clicked */ onClick: () => void } /** * @category Componen ...

Dynamic typing depending on the individual elements within an array

I am working with some extensions: type ExtensionOptions = { name: string } type BoldOptions = ExtensionOptions & { boldShortcut?: string } type ItalicOptions = ExtensionOptions & { italicShortcut?: string } type LinkOptions = ExtensionOptions &am ...

Struggling to link Angular frontend with Java backend?

Trying to make an API call in the backend, but encountering an error with no clear cause identified. The issue arose after configuring the spring security in the backend. The call should activate Preflighted requests OPTION. @Configuration @EnableWebSecur ...

Tips for effectively simulating the formik useFormikContext function while writing unit tests using jest

I've created a simple component (shown below) that aims to fetch data from the Formik FormContext using the useFormikContext hook. However, I'm facing some challenges when writing unit tests for this component. It requires me to mock the hook, w ...

Nextjs REACT integration for self-service registration through OKTA

Attempting to integrate the Okta SSR feature for user sign-up in my app has been challenging as I keep encountering this error message: {"errorCode":"E0000060","errorSummary":"Unsupported operation.","errorLink& ...

The TypeScript error occurs when attempting to assign a type of 'Promise<void | Object>' to a type of 'Promise<Object>' within a Promise.then() function

I'm currently working on a service to cache documents in base64 format. The idea is to first check sessionStorage for the document, and if it's not there, fetch it from IRequestService and then store it in sessionStorage. However, I've encou ...

Is it possible to validate input from a parent component in Angular and pass it on to a nested child component?

I have a form with reactive validation where the submit button is in the grandparent component. I am trying to figure out how to check the validation status of my child component using ViewChild or any other method. It seems like an impossible task to me, ...

Bringing in the Ionic ToastController to a TypeScript class

I'm unsure if it's feasible or wise, but I am currently developing an Ionic 3 project and I want to encapsulate "Toast" functionality within a class so that I can define default values and access it from any part of the application. Is there a ...

Switching Next.js JavaScript code to Typescript

I am currently in the process of transforming my existing JavaScript code to TypeScript for a web application that I'm developing using Next.Js Here is the converted code: 'use client' import React, { useState, ChangeEvent, FormEvent } fro ...

Guide on incorporating text input areas into specific positions within a string

Looking for a way to replace specific words in a string with input fields to enter actual values? For example... Dear Mr. [Father_name], your son/daughter [name] did not attend class today. This is what I want it to look like... Dear Mr. Shankar, your ...

Utilizing a .match() function may result in the object being potentially 'null'

I have been developing a series of validation functions for my static site generation tool. One of these functions involves using various .match() methods to analyze HTML header tags. Here is the current state of the validation function: // 2c. Check that ...

Creating a dynamic number of properties with different names in Typescript can be achieved by using a loop

I have a requirement for enabling type checking on a specific class Here is the relevant code snippet: class FlightFilter implements Filter { get filters() { return { departTime: { name: 'Departure Time', type: FilterTypes.Range }, ...

Arranging Firebase posts in UITableView based on date (latest first)

I have been attempting to arrange my posts in Firebase with the newest ones appearing first for quite some time now. While I am aware that Firebase automatically does this when using childByAutoId(), I suspect that the issue lies in how I'm fetching t ...

Can you provide guidance on adjusting the dimensions of the Carousel element within the ShadCN UI?

My React component setup currently includes the following: "use client"; import Autoplay from "embla-carousel-autoplay"; import { Card, CardContent } from "@/components/ui/card"; import { Carousel, CarouselContent, ...

Nested asynchronous functions in TypeScript

profile.page.ts: username: string; totalScore: number; ... loadUserData() { this.spinnerDialog.show(); this.firebaseServie.loadUserData().then(() => { this.username = this.sessionData.getUser().getUsername(); this.totalSco ...

Is it possible to update a MobX state when a message is received from Firebase in the background?

I've set up Firebase in my project like this: import { initializeApp } from 'firebase/app'; import { getMessaging, getToken, onMessage, isSupported } from 'firebase/messaging'; import store from './flag'; ...

What is the process for changing the text in a text box when the tab key on the keyboard is pressed in

When a user types a name in this text box, it should be converted to a specific pattern. For example, if the user types Text@1, I want to print $[Text@1] instead of Text@1$[Text@1]. I have tried using the keyboard tab button with e.keyCode===9 and [\t ...

The header of the function specifies only one parameter, however the function call necessitates three

Within my Typescript code, I have a function defined as follows: export const func: AWSLambda.APIGatewayProxyHandler = async ( arg ): Promise<AWSLambda.APIGatewayProxyResult> => { During a unit test, when I attempt to call this function like fu ...

Converting an object into an array using Angular

Can someone assist me with this code issue? I am currently using "@angular/cli": "~12.0.5". The issue lies within the createArray method, where I need to convert an object into an array. However, I encounter an error specifically at & ...

Bar chart in Chart.js becomes crowded and illegible on smaller screens due to overlapping bars

Hello there! I've encountered an issue where the bar chart overlaps when the screen width is too low. It seems to be related to the maintainAspectRatio property, which I set to false because I wanted the charts to shrink only in width, not in both axe ...