Get the most recent two files from a set

I am currently facing a challenge in retrieving the first 2 documents from a collection in google cloud firestore. My current approach involves using the timestamp of the latest document and then calculating the time range to fetch the desired documents.

let firstStamp: number = [example timestamp in ms]

const query: any = await admin.firestore().collection('collection').where('timestamp', '<', firstStamp);
let documents: any;
query.where('timestamp', '>', firstStamp - 15000);
return query.get().then(result => {
    if (result.size === 0) {
        log(`No data. If this happens i've done something wrong with my query.`);               
        return;
    };

    documents = result.docs;
});   

Despite not encountering any error messages or logs, this solution is not yielding the expected results. Can anyone identify what might be going wrong?

If there are alternative methods to achieve this task more effectively, I would greatly appreciate some guidance.

Answer №1

If you store a timestamp field in each document indicating its creation time, querying the two most recent documents is straightforward. By using the orderBy() and limit() methods as shown below:

import { collection, query, orderBy, limit, getDocs } from "firebase/firestore";

const q = query(collection(db, "collection"), orderBy("timestamp", "desc"), limit(2));

const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
  // doc.data() will always have a value for query doc snapshots
  console.log(doc.id, " => ", doc.data());
});

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

Option to modify the arguments of a method in a parent class

I encountered an interesting problem recently. I have two classes: class Animal { public talk() { console.log('...'); } } and class Dog extends Animal { public talk(noise: string) { console.log(noise); super.talk() } } The i ...

The global declaration of Typescript is only accessible within the node_modules/@types directory

Scenario As I develop an npm package using Typescript, I include types that are shipped alongside the library in the following structure: my-package |- index.js |- index.d.ts |- package.json The index.d.ts file includes global declarations like: declare ...

[Vue warning]: The property "text" was accessed during rendering, however it is not defined on the current instance using Pug

Looking for some guidance from the Vue experts out there. I've recently started working with Vue and I'm attempting to create a view that verifies an email with a unique code after a user signs up. Right now, my view is set up but it's not c ...

The loading of npm installed Firebase in Angular4 is not successful

I am currently facing an issue while trying to integrate npm installed Firebase with my Angular4 application. I have successfully installed the latest version of Firebase (version 4.1.1) using npm and verified that the installation was successful. Below is ...

Outputting a JS file per component using Rollup and Typescript

Currently, I am in the process of developing a component library using React, TypeScript, and Rollup. Although bundling all components into a single output file index.js is functioning smoothly, I am facing an issue where individual components do not have ...

Is it feasible to maintain a persistent login session in Firebase without utilizing the firebase-admin package through the use of session cookies?

Currently, I am integrating Firebase into my next.js application for user login functionality. The issue I am facing is that users are getting logged out every time they switch paths within the site. Even though their session cookie has not expired, if the ...

Is there a way to retrieve the value of an option passed by serverless CLI in serverless.ts file?

As I explored the serverless framework with serverless.ts for configuration, a certain question came to mind. When utilizing the serverless CLI, passing values can be done in the following way: serverless offline --stage prod In the serverless.yml file, ...

Testing Angular components using mock HTML Document functionality is an important step in

Looking for help on testing a method in my component.ts. Here's the method: print(i) { (document.getElementById("iframe0) as any).contentWindow.print(); } I'm unsure how to mock an HTML document with an iframe in order to test this meth ...

Edge Runtime does not permit the use of Dynamic Code Evaluation functions such as 'eval', 'new Function', and 'WebAssembly.compile'

My project involves the implementation of NextUI components. I incorporated the Select component from NextUI, and during development mode, everything functioned flawlessly. However, upon completion of development and attempting to build the project, I enc ...

The term 'required' is not recognized as an identifier. There is no member by the name of '__type' in the definition

When working on my HTML template in the visual code editor, I encountered the need to declare a variable with type any? https://i.stack.imgur.com/Jq5az.png product-form.component.html <div class="row"> <div class="col-md-6"> <for ...

Issue with accessing form in Angular 6 Reactive forms for custom validator functionality

I am facing an issue with creating a password validation for reactive forms in Angular. Every time I try to verify the password, I get a “Cannot read property 'get' of undefined” error in the console. I have tried different methods to access ...

Unable to run `create-react-app` with the `--template typescript` option

Every time I try to execute the following command: npx create-react-app my-app --template typescript only a JavaScript project is created, without any .tsx files. After consulting the CRA's TypeScript guide, it appears that the command requires Node ...

Ways to modify the CSS of an active class within a child component when clicking on another shared component in angular

In my HTML template, I am encountering an issue with two common components. When I click on the app-header link, its active class is applied. However, when I proceed to click on the side navbar's link, its active class also gets applied. I want to en ...

Encountering the error `signed_request_invalid_format` while attempting to retrieve GCP bucket content through Cloud CDN

Using signed cookies to access restricted files from a GCP bucket via Cloud CDN, I have implemented the following function to sign the cookie: signCookie(urlPrefix: string, keyName: string, key: string, expires: number) { // Base64url encode the url pr ...

Encountering a TS1005 error while trying to import types from a type definition file

Within my project, one of the libraries called parse5 is providing typing information in .d.ts files. The current syntax used to import types is causing several TypeScript errors during application runtime because TypeScript does not seem to recognize this ...

Enumerate the names of the private properties within the class

I am working on a problem where I need to use some of the class properties as values in a map within the class. In the example below, I have used an array instead of a map because when a property is marked private, it is not included in the keyof list. How ...

Using ngFormModel with Ionic 2

How can I properly bind ngFormModal in my Ionic 2 project? I am facing an issue while trying to import it on my page, resulting in the following error message: Uncaught (in promise): Template parse errors: Can't bind to 'ngFormModel' since ...

Exploring alternative methods for accessing object values in TypeScript using a string object path without relying on the eval function

If we have an object in JS/typescript structured like this: var obj = { a: { b:{ c:1 } } } And a string "b.c" is given, how can we evaluate this using only the variables provided and retrieve the value 1 from the object without rel ...

Developing maintenance logic in Angular to control subsequent API requests

In our Angular 9 application, we have various components, some of which have parent-child relationships while others are independent. We begin by making an initial API call that returns a true or false flag value. Depending on this value, we decide whether ...

Apply a CSS class once a TypeScript function evaluates to true

Is it possible to automatically apply a specific CSS class to my Div based on the return value of a function? <div class="{{doubleClick === true ? 'cell-select' : 'cell-deselect'}}"></div> The doubleClick function will ret ...