【问题标题】:How do to retrieve all documents in a collection and see if a document exists in firebase Firestore?如何检索集合中的所有文档并查看 Firebase Firestore 中是否存在文档?
【发布时间】:2020-06-23 18:30:29
【问题描述】:

架构: This is how my schema looks

当前实施:

    for (let i=0; i<data.length; i++) {
            try
            {
                
                var ifPresent = db.collection("Safes-Hardware").doc(data[i]['Mac address Check']);
                ifPresent.get()
                .then(async (doc)=>{

                            if (!doc.exists) 
                            {
                                // Do stuff
                            }
                            else
                            {
                                //Do stuff
                            }
                            return { message: "Success is within the palm of our hands." } 
                        }

            }

问题: 即使这段代码完成了这项工作,对于数组中的每个数据,我都在进行查找,这会导致套接字挂断。(有时) 所以我想我会一次性获取集合中的所有文档,将其存储在本地并查找本地是否存在文档,而不是每次都查询数据库。

问题: 我该如何实现?

【问题讨论】:

    标签: javascript node.js firebase google-cloud-firestore


    【解决方案1】:

    你可以只使用collection("Safes-Hardware").get().then(),你可以将数据保存在本地。

    let collection = []
    db.collection("Safes-Hardware").get().then(function(querySnapshot) {
        collection = querySnapshot.map((doc) => ({
                id: doc.id,
                ...doc.data()
              }))
    });
    

    那你就可以用collection来搜索你想要的,可能是这样的

    data.forEach( doc => {
       let x = collection.find(v => v.id === doc['Mac address Check'])
       if(x){
        //it exists
       }else{
         // not exists
       }
    })
    

    但请注意,在客户端使用 o(n^2) 操作会影响带宽或请求数量

    【讨论】:

      猜你喜欢
      • 2019-04-19
      • 1970-01-01
      • 1970-01-01
      • 2019-12-28
      • 2023-01-05
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      相关资源
      最近更新 更多