Home > Blockchain >  Firestore query is only returning 1 doc
Firestore query is only returning 1 doc

Time:02-15

I have written a simple Firebase function to get all the docs in a collection called 'events'. My code:

export const requestuserroute2 = functions
    .region("europe-west6")
    .https.onRequest(async (request, response) =>{
      const uid = String(request.query.uid);
      const db = admin.firestore();
      db.collection("position_data")
          .doc(uid).collection("events")
          .get()
          .then((snapshot) => {
            snapshot.forEach((doc) => {
              const data = JSON.stringify(doc.data(), replaceg);
              response.send(data);
            });
          });
    });

replaceg is a function to delete data where the key is 'g'. (Please ignore)

It only returns the contents of the first doc (ending in *Mnija):

{"timeStamp":1644760476557,"coordinates":{"_latitude":13.1,"_longitude":31.562},"sid":"b72b98b0-7130-41bd-9c67-ed79128c070a","type":"pause_off"}

What I expect is multiple lines of data, 1 for each document. The code does not seem to be looping through the documents. So where am I going wrong? enter image description here

CodePudding user response:

It's because you're sending a response to the client inside the loop:

snapshot.forEach((doc) => {
  const data = JSON.stringify(doc.data(), replaceg);
  response.send(data);
});

The first time through the loop it sends the data to the client, and all other times the call is ignored (it should actually be raising an error, but ¯\_(ツ)_/¯).

To send all documents to the caller, build a single response in the loop and then send that:

db.collection("position_data")
    .doc(uid).collection("events")
    .get()
    .then((snapshot) => {
      const result = snapshot.docs.map((doc) => {
        return JSON.stringify(doc.data(), replaceg);          
      });
      response.send(result);
    });
  • Related