Ad

How To Stop ForEach When I Find The Data I Want To Get In Firebase?

I want to get a data from Firebase. But I know Firebase use forEach to search a data in the database.

  db.collection('users').get()
  // eslint-disable-next-line promise/always-return
    .then((snapshot) => {
      snapshot.forEach((doc) => {
        console.log(doc.id, '=>', doc.data());
        myData.push(doc.data().first);
      });

      const title = myData.find( e => e === 'Dennis');
      res.render('index', {title});
      // return null;
    })
    .catch((err) => {
      console.log('Error getting documents', err);
    });

you can see forEach will search every doc.data().first in the database. but I thought this is a very inefficient way to search for data in the database. I want forEach stops when it finds the data I want to get.

Ad

Answer

According to the API documentation for DataSnapshot.forEach, there is no way to terminate the loop. Even if you could, it would still incur a read for each matching document from the query. This means you are still transferring every document to the client, no matter what happens with forEach.

If you want to be efficient, only query for the documents you know you want to receive. In your case, if you want to find a document where a specific field contains a string "Dennis", you should query for just those documents, as described in the documentation.

Ad
source: stackoverflow.com
Ad