0

I have following cloud function to get data from the firebase datastore but it doesn't compile and am not sure how to fix this.

import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';

admin.initializeApp(functions.config().firebase);

const db = admin.firestore();
const usersObj = db.collection('users')

export const getUsers = async () => {
    let allUsers: Array<any> = [];
    await usersObj.get().then(users => {
        users.forEach(user => {
            allUsers[user.id] = user.data();
        });
    });
    return allUsers;
}

error: error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'. allOrders[order.id] = order.data();

3
  • Is user.id a number? Commented May 15, 2019 at 7:29
  • @Héctor its a string... GUID Commented May 15, 2019 at 7:31
  • I think that's the problem. Array index should be a number. You could change allUsers to be an object, or use forEach index as array index instead of user's GUID Commented May 15, 2019 at 7:33

2 Answers 2

1

If you want to transform your array elements into a new array, you could also use Array.map.

allUsers = users.map(user => user.data());
Sign up to request clarification or add additional context in comments.

3 Comments

actually what I wanted to do was something like users.forEach(user => { allUsers.push({ id: user.id, ...user.data() }); }); I don't know how to do it using .map
Something like this: allUsers = users.map(user => Object.assign({ id: user.id }, user.data()));
doesn't seems to work. getting error Property 'map' does not exist on type 'QuerySnapshot'.
0

You can't index an array using a string. To solve it, you can:

Use forEach index as array index:

users.forEach((user, i) => {
    allUsers[i] = user.data();
});

or push items to the allUsers array:

users.forEach(user => {
    allUsers.push(user.data());
});

2 Comments

great. thanks... I was using push before but removed it during fixing other type issues with allUsers...
great, glad to help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.