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.
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.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM