Firebase functions are giving me a headache with this error message: "TypeError: elements.get is not

Encountering the following error log while executing a firebase function to fetch documents and values from the recentPosts array field.

Error: Unknown error status: Error: Unknown error status: TypeError: elements.get is not a function
    at new HttpsError (/srv/node_modules/firebase-functions/lib/providers/https.js:90:19)
    at admin.firestore.collectionGroup.where.get.then.catch.error (/srv/lib/index.js:71:15)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7)

Class:

class PostTable {
   public commentCount : number;

   public dateTime : number;

   public docId : string;

   public post : string;

   public userId : string;

   public userName : string;

   constructor(commentCount: number, dateTime: admin.firestore.Timestamp, docId: string, post : string, userId : string, userName : string) {

       this.commentCount = commentCount
       this.dateTime=  dateTime.toDate().getTime()
       this.docId=docId
       this.post=post
       this.userId=userId
       this.userName=userName
   }
}

function:

export const getPosts = functions.https.onCall((data, context) => {

   if (!context.auth) {
      // Throwing an HttpsError so that the client gets the error details.
      throw new functions.https.HttpsError('failed-precondition', 'The function must be called ' +
          'while authenticated.');
    }

    let responseCollection : PostTable[] = []

         admin.firestore().collectionGroup('recentPostColl').where('users', "array-contains",context.auth.token.name)
                                 .get()

         .then(collectionOfPosts => {

            if(!collectionOfPosts.empty)
            {

               collectionOfPosts.forEach(element => {

                  let collection : Map<String, Object>[] = element.get('recentPosts')

                  collection.forEach(elements => {

                     try {
                        const p : PostTable = new PostTable(elements.get('commentCount')as number, elements.get('dateTime') as admin.firestore.Timestamp
                        ,elements.get('docId') as string,elements.get('post') as string, elements.get('userId') as string, elements.get('userName') as string);

                        const stamp : admin.firestore.Timestamp = elements.get('dateTime') as admin.firestore.Timestamp

                        const date : Date = stamp.toDate()

                        if(date.getTime() > new Date(data.date).getTime())
                        {

                              responseCollection.push(p)
                        }
                     } catch (error) {
                        throw new functions.https.HttpsError(error, 'Constructor error');
                     }

                  });
               });

            }


   })

   .catch(error =>{
      throw new functions.https.HttpsError(error, 'code error');
   })

   return responseCollection


})

Document:

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

Answer №1

The variable collectionOfPosts in your code represents a QuerySnapshot object. You are using its forEach method to iterate through the QueryDocumentSnapshot objects it contains. Using the get() method, you extract a specific field from that snapshot, which is essentially a plain JavaScript array type since the field is an array. It's important to note that these fields are not strongly typed arrays; they are plain JavaScript types rather than TypeScript collection types. Therefore, you cannot directly convert plain JavaScript types into TypeScript collection types.

To work with this field in a safe and specific manner within JavaScript:

let collection: object[] = element.get('recentPosts')

You can then access elements in the collection as you would with a regular array:

let item = collection[0]

or iterate over it just like any other JavaScript array.

Each item within the collection is of type object, allowing you to interact with them as standard JavaScript objects.

If you wish to utilize TypeScript collection types instead, you will need to write custom code to convert the plain JavaScript arrays and objects into their TypeScript counterparts.

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

Condensed JQuery condition code for "if" statement

This piece of code is designed to sequentially display 10 questions and control the visibility of each question using the CSS class .hideme. It also sends metrics data to Google Analytics. Although it functions properly, I feel like the code is too leng ...

How to prevent value overwriting when adding dynamic fields in Angular 7?

In my current project using Angular, I am tasked with setting up configuration using 4 specific fields: Department Name (select option) Service Name (select option) Status (text input) Level (text input). I need to be able to add multiple sets of these ...

Returning draggable elements to their original placement

I'm looking to create a custom function that resets my draggable elements to their original positions when invoked. This is not related to the built-in revert functionality. $('.drag').draggable({ stack: ".drag", snap: ".dro ...

Tips for choosing a block using Puppeteer

Trying to retrieve the height of a series of blocks using Puppeteer, I encountered an issue where I couldn't select my block in page.evaluate() due to an error. The code snippet in question is as follows: (async () => { const browser = aw ...

Attempting to modify the color of a selected Three.js object causes all objects in the scene to have their colors altered

For example, check out this JSFiddle link. The interesting part occurs during the mousedown event: var hits = raycaster.intersectObjects( [object1, object2, object3] ); if ( hits.length > 0 ) { console.log(hits[ 0 ].object) hits[ 0 ].object.m ...

I have the latitude and longitude for both the shop and user, and I am looking to display a list of shops in order based

Currently, I have the latitude and longitude for both my shop and the user. My objective is to display a list of shops that fall within the geographic area between the user's location and the shop's coordinates using Sequelize ORM. Can you provid ...

Setting up Emotion js in a React TypeScript project using Vite 4

Currently, I am in the process of transitioning from Webpack to Vite for my React Typescript application. I have been attempting to integrate Emotion js into the project. "@vitejs/plugin-react": "^4.0.1", "vite": "^4.3.9 ...

Reorganizing an array using a custom prioritized list

Is it possible to sort an array but override precedence for certain words by placing them at the end using a place_last_lookup array? input_place_last_lookup = ["not","in"]; input_array = [ "good", "in", "all&qu ...

Struggling to use the innerHTML method to update a div within another div element?

<!DOCTYPE html> <html> <head> <title>Business Information Card</title> <script type="text/javascript"> window.onload = init; function init(){ var button = document.getElementById("populate ...

I'm getting a JS error saying that the variable "var" is not defined. Does anyone know how I can

Here is the code I am using to dynamically create a sitemap.xml file when accessing /sitemap.xml database = firebase.database(); var ref = database.ref('urls'); ref.on('value', gotData, errData); function errData(err){ ...

Unable to locate dependencies while testing the react package locally

Recently, I came across this npm package designed for React using Typescript. To debug it locally, I initiated npm link in a new React project but encountered an error: https://i.sstatic.net/nObH6.png I suspect it may not be reading the packages correct ...

Ways to reload an independent page in order to access PHP session variables:

Starting off, I want to mention that my approach may not be the most efficient. As a novice in JavaScript and PHP, I am aware that there are better and simpler ways to achieve what I'm attempting. The issue seems to be related to session variables an ...

Unexpected behavior with onKeyPress in React-Native Windows resulting in missing key press events

Currently, I am working on a Windows app using react-native version 0.54.0. For one of the functionalities, I have incorporated a TextInput element and would like to use onKeyPress. Here is my code snippet: <TextInput ref = { this.setTextInputRef } on ...

When attempting to view the PDF file, it appears completely void

After spending countless hours on this task, I'm still not making any progress. My goal is to download a PDF file from my server while currently running the operation on localhost. However, whenever I open the downloaded PDF, all I see is a blank whit ...

Unable to clear cache in Next.js using RTK query

Currently, I am utilizing Next.js along with next-redux-wrapper and RTK Query. My application is performing external API requests on the server side. The implementation of the request looks like this: CompaniesPage.getInitialProps = initialPagePropsWithCom ...

What is the best way to compare two date strings with the format dd/mm/yyyy using JavaScript?

When attempting to compare a "Date" type of data with an "Any" type of data, the comparison is not functioning as expected. The date is retrieved in the following code: var today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); v ...

Implementing diverse color gradients to individual vertices within a geometry using three.js

My goal is to enhance the functionality of this code snippet so that when the button is clicked, the selected mesh's neighborhood vertex is highlighted with a gradient effect. function addSphere() { var position = new Array(); var notAboveGround = tr ...

Utilizing Global Variables and Passing Values in Ionic 3

It seems like my issue is rather straightforward, but there is definitely something eluding me. After logging in, I need to store a TOKEN for HTTP requests in a global variable. Upon successful login, the HTTP get method returns an object with the HTTP co ...

Using Ajax to implement Basic Authentication for securely accessing an https-protected webpage without requiring users to manually enter their username and password in a

Is there a way to access and display a website page hosted at this URL - , without encountering any authentication dialog box from my application on the same network? I have been unable to bypass the username and password entry request. I successfully imp ...

What is the best way to send a file object to a user for download?

When working within a route: app.get('some-route', async (req, res) => { // ... } I am dealing with a file object called file, which has the following structure: https://i.stack.imgur.com/ByPYR.png My goal is to download this file. Cur ...