The 'then' property is not found on the type 'CloudFunction<Change<DocumentSnapshot>>'

Encountered an error: The property 'then' does not exist on type 'CloudFunction>' in my Firebase cloud function. Does anyone have a solution?



exports.rebuildFormTriggerClientDetails = functions.firestore.
document('clientDetails/{details}').onUpdate((change)  => {
  const afterDoc = change.after.data();
  const documentId = change.after.id

  if (afterDoc)

  {
    let docUsers = db.collection("clientDetails").doc(documentId);
    //var userMap: {[key: string]: any} = {};
    let caseArray: Array<string>;
    caseArray = afterDoc.CaseRefArray;

    for (var valCase of caseArray) {
      console.log(valCase); 
      console.log(documentId);

        createObjectDocument(docUsers,valCase);
    }
  }

}).then(() => {
  console.log("Successfully updated document!");
}).catch((error: any) => {
  console.error("Error updating document: ", error);
});

Could the createObjectDocument function be causing the error?


function createObjectDocument(document: any, caseNumber: String)

{
  document.get().then(function(doc: any) {
    if (doc.exists) {
        console.log("Document data:", doc.data());
        for (let [key, value] of Object.entries(doc.data())) {
          console.log(`${key}: ${value}`);
         if (key != "CaseRefArray")
         {
          db.collection("casesToExport").doc(caseNumber).update({key : value });
         }
        }
    } else {
        console.log("No such document!");
    }
}).catch(function(error: any) {
    console.log("Error getting document:", error);
});

}

Answer №1

Modify your code as shown below:

exports.rebuildFormTriggerClientDetails = functions.firestore.
document('clientDetails/{details}').onUpdate((change)  => {
  //const before = change.before;  // DataSnapshot before the change
  const afterDoc = change.after.data();
  const documentId = change.after.id

  if (afterDoc)

  {
    let docUsers = db.collection("clientDetails").doc(documentId);
    //var userMap: {[key: string]: any} = {};
    let caseArray: Array<string>;
    caseArray = afterDoc.CaseRefArray;

    for (var valCase of caseArray) {
      console.log(valCase); 
      console.log(documentId);

        createObjectDocument(docUsers,valCase);
    }
  }

});



function createObjectDocument(document: any, caseNumber: String)

{
  document.get().then(function(doc: any) {
    if (doc.exists) {
        console.log("Document data:", doc.data());
        for (let [key, value] of Object.entries(doc.data())) {
          console.log(`${key}: ${value}`);
         if (key != "CaseRefArray")
         {
          db.collection("casesToExport").doc(caseNumber).update({key : value })
            .then(() => {
                console.log("Successfully updated document!");
            }).catch((error: any) => {
                console.error("Error updating document: ", error);
            });
         }
        }
    } else {
        console.log("No such document!");
    }
}).catch(function(error: any) {
    console.log("Error getting document:", error);
});

}

Ensure that your .then() call is placed correctly when updating the document in your database, as shown in your createObjectDocument() function

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

Unleash the power of zod by seamlessly accessing both parameters and queries

In the zod-middleware documentation, an example is provided: export async function endpointCode(req: TypedRequestBody<typeof bodySchema>, res: Response) { const typedBody = req.body; return res.json(typedBody); } This example demonstrates access ...

Encountered a unique error code "TS1219" in Visual Studio

Recently, I made some changes to the architecture of my UI project and encountered a slew of errors (TS1219 and TS2304). Could the culprint be a poorly configured tsconfig.json file, or is it something else entirely? Despite encountering no issues when dec ...

Dependency Injection: The constructor of the injectable class is called multiple times

There are multiple classes that inject the TermsExchangeService: import {TermsExchangeService} from './terms-exchange.service'; @injectable() export class TermsExchangeComponent { constructor( private termsExchangeService: TermsExchan ...

Leveraging WebStorm's TypeScript support in conjunction with node_modules

Attempting to set up a TypeScript project in WebStorm to import a Node.js module has been a struggle. I made sure to download the necessary TypeScript definition in settings and specified --module commonjs in the compiler settings. However, I keep running ...

The Ionic 5 app features a white iframe that functions perfectly on the web platform

Whenever I run my web application's function, the iframe is displayed. However, on Android, all I see is a white screen. Can anyone assist with resolving this issue? HMTL html <ion-content> <ion-button expand="full" color="warning" (clic ...

What is the best approach for handling server-side validation errors in Angular when making an HTTP call?

After following different tutorials, I have created a service that can transmit login details to the backend for validation and processing. Although I am able to generate appropriate error codes based on user input, I find myself wondering what to do next. ...

Best practices for setting up PDAs in the Solana Anchor framework

Trying to create a basic Solana Program using Rust/Anchor that involves a PDA is causing a CPI error upon invocation, even though there doesn't appear to be any CPI happening (possibly due to the PDA account initialization). Below is the Program code ...

Leverage TypeScript's enum feature by incorporating methods within each enum

In my TypeScript file, I have defined various events and interfaces: export type TSumanToString = () => string; export interface ISumanEvent { explanation: string, toString: TSumanToString } export interface ISumanEvents{ [key: string]: ...

What are the distinctions in type-narrowing when assigning values using ternary expressions versus if-else statements?

It seems that the type checker is handling the typing of m in print() differently based on whether m was assigned through a ternary expression or an if-else statement. What sets apart the first line in the print() function from the commented code below it? ...

Blurry text issue observed on certain mobile devices with Next.js components

There continues to be an issue on my NextJS page where some text appears blurry on certain mobile devices, particularly iPhones. This problem is only present on two specific components - both of which are interactive cards that can be flipped to reveal the ...

Issue: The 'typeOf' function is not exported by the index.js file in the node_modules eact-is folder, which is causing an import error in the styled-components.browser.esm.js file in the node_modulesstyled

Every time I attempt to start running, there are issues with breaks in npm start (microbundle-crl --no-compress --format modern,cjs) I have attempted deleting node_modules and package-lock.json, then running npm i again but it hasn't resolved the pro ...

Initial compilation of Angular 2 project with lazy-loaded submodules fails to resolve submodules

I'm working on an Angular 2 project (angular cli 1.3.2) that is structured with multiple modules and lazy loading. In my main module, I have the following code to load sub-modules within my router: { path: 'module2', loadChildren: & ...

Leveraging jQuery within a webpack module shared across multiple components, located outside the webpack root directory

When working with multiple layouts that rely on shared typescript files, it is important to ensure these files are accessible across different layouts using webpack. While attempting to include jquery in my ajax.ts, I encountered the following error: ERR ...

Instructions on transferring information from the app.component to its child components

I am currently working with Angular 6 and I have a specific requirement. I need to send data retrieved from an external API in my app.component to other child components. Instead of repeatedly calling the common API/service in every component, I want to ma ...

Exploring the capabilities of AngularJS2's formGroup and formControlName functionality

Exploring the world of AngularJS2, I recently created a sign-up page utilizing formGroup formControlName, but encountered an issue with passing null values to the object. HTML code: <div class="col-md-8 col-md-offset-2"> <form [formGroup]="m ...

Different ways to determine if a given string exists within an Object

I have an object called menu which is of the type IMenu. let menu: IMenu[] = [ {restaurant : "KFC", dish:[{name: "burger", price: "1$"}, {name: "french fries", price: "2$"}, {name: "hot dog", d ...

What is the proper way to write a function that verifies the presence of a key in an object and then retrieves the associated value?

After holding out for a while hoping to stumble upon the solution, I've decided to give it a shot here on SO since I haven't found it yet. import { PDFViewer, MSViewer } from './viewerclasses' //attempting to incorporate a union of key ...

Alert: Zone.js has identified that the ZoneAwarePromise '(window|global).Promise' has been replaced with polyfills. Kindly address this issue

Recently, I updated my Angular application from version 8 to 9. After updating the packages and successfully compiling the application, I encountered an error message in the Chrome browser console: Error: Zone.js has detected that ZoneAwarePromise `(wind ...

Utilizing two DTOs for a single controller in NestJS

I'm having trouble retrieving and transforming different types of dtos from the body. My goal is to extract and transform firstDto if it's incoming, or convert secondDto if that's what's being received. However, my current code isn&apos ...

Injecting a service into a parent class in Angular 6 without the need to pass it through the constructor

Can anyone provide guidance on how to incorporate a service with multiple dependencies into an abstract class that will be inherited by several classes, in a more streamlined manner than passing it through all constructors? I attempted to utilize static m ...