how to break querySnapshot on Firestore?

主宰稳场 提交于 2020-08-10 19:44:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!