简体   繁体   中英

How do to retrieve all documents in a collection and see if a document exists in firebase Firestore?

Schema: This is how my schema looks

Current Implementation:

    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." } 
                        }

            }

Problem: Even though this code does the job, for each data in the array I'm doing a lookup, and this results in a socket hang-up.(sometimes) So I'm thinking I'll get all the documents in the collection in one go, store it locally and look up if a documents exists locally instead of querying the database every time.

Question: How do I implement this?

You can just use collection("Safes-Hardware").get().then() and you can save the data locally.

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

then you can use collection to search for what you want, maybe like this

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

But take care you are compromising bandwidth or number of requests with o(n^2) operation in the client side

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM