Need to get an array of all Id's in a firebase collection

Viewed 147

Have the method below that extracts the Id's from the firebase collection and pushes it to an array, BUT it makes each document into an array. In other words- if i have 100 documents in the collection - it makes 100 arrays inside the array IDarray. I just need one array to keep it more efficient. Maybe:)

     db.collection('Customers')
     .orderBy('createdAt', 'asc')
     .get()
     .then((data) => {
                      let IDarray = [];
                      data.docs.forEach(doc =>{
                      IDarray.push(+doc.id);
                      });
       return [IDarray];
     })

I can certainly make this work but if anyone knows of a better way so the system is not generating all the extra arrays it would be appreciated. (Back story: the IDarray is being generated as int because my Id's for the collection are a number sequence) Cheers!

2 Answers

Try this:

  db
    .collection("Customers")
    .orderBy("createdAt", "asc")
    .get()
    .then((data) => {
      let IDarray = [];
      data.docs.forEach((doc) => {
        IDarray.push(+doc.id);
      });
      return IDarray;
    });

It works just fine for me.

Or here's an ES6-y way of doing it:

  db
    .collection("Customers")
    .orderBy("createdAt", "asc")
    .get()
    .then(({ docs }) => docs.map(({ id }) => +id));

Seems like you don't need another array wrapper for the return value:

    return IDarray;

Notice no square braces. Just return the array as-is.

Related