问题
I need to break querysnapshot loop. Is it possible?
I tried with for loop. but the below error is coming.
How to fix this error or Is there any way to break snapshot loop?
code
return query.get()
.then((snapshot) => {
for(const doc of snapshot) {
let data = doc.data()
if (data.age == 16) {
break;
}
}
error
Type 'QuerySnapshot' must have a 'Symbol.iterator' method that returns an iterator.
回答1:
You can use the docs property of the QuerySnapshot, which returns an array of all the documents in the QuerySnapshot.
For example, with a for loop:
return query.get()
.then((snapshot) => {
const snapshotsArray = snapshot.docs;
for (var i = 0; i < snapshotsArray.length; i++) {
const data = snapshotsArray[i].data()
if (data.age == 16) {
break;
}
}
}
or with a for-of:
return query.get()
.then((snapshot) => {
const snapshotsArray = snapshot.docs;
for (const snap of snapshotsArray) {
const data = snap.data()
if (data.age == 16) {
break;
}
}
}
回答2:
Docs say that QuerySnapshot<T> is not an iterator/async iterator so you can't use it like one. Seems like the only way to iterate over it is with forEach which doesn't seem to provide a way of "early breaking".
来源:https://stackoverflow.com/questions/60260237/how-to-break-querysnapshot-on-firestore