Home > database >  send a firebase collection of the doc id's as an array through an endpoint
send a firebase collection of the doc id's as an array through an endpoint

Time:03-02

how od i send only the names of the documents in the collection through the endpoint?

  import { db } from '../../lib/firebase';


export default async function handler(req, res) {
  const user = await db
    .collection('readings')
    .get();
  if (!user.exists) {
    return res.status(404).json({});
  }

  return res.status(404).toArray(user.id);
}

I need to call the endpoint and then have the information sent to the frontend. The collection of readings has a bunch of documents with all the account id's

how do I retrieve only the id's from the collection?

CodePudding user response:

You are querying on a CollectionReference that'll return all the documents in the collection so you cannot (and don't have to) use exists. Then you can just map() all documents IDs and send them back. Try refactoring the code as shown below:

export default async function handler(req, res) {
  const qSnapshot = await db
    .collection('readings')
    .get();

  const documentIds = qSnapshot.docs.map(d => d.id)

  return res.status(200).json({ data: documentIds });
}

If you are using Admin SDK then you can also use select() to get Document IDs only. Checkout:

How to get a list of document IDs in a collection Cloud Firestore?

  • Related