Firestore break out of a query

72 views Asked by At

I have code as below to not to write to DB if the same post has already been posted.

I put a return but self.addtoDB() is still executed. What is the right way to check for an existing post and not write to DB if it exists?

db.collection("posts")
    .where("ytid", "==", self.youtubeId)
    .get()
    .then(function(querySnapshot) {
      querySnapshot.forEach(function(doc) {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, " => ", doc.data());
        alert("This gameplay has already been posted");
        return;
      });
    })
    .catch(function(error) {
      console.log("Error getting documents: ", error);
    });
  self.addToDB();
1

There are 1 answers

0
Doug Stevenson On BEST ANSWER

Like all functions that return a promise, get() returns immediately, the callback you provide to then will be invoked some time later after the query completes. Your code continues on to execute self.addToDB() immediately after that, without waiting for the results. You should instead do all of your conditional processing inside that callback.

    .then(function(querySnapshot) {
      if (querySnapshot.docs.length > 0) {
        const doc = querySnapshot.docs[0];
        console.log(doc.id, " => ", doc.data());
        alert("This gameplay has already been posted");
      }
      else {
        self.addToDB();
      }
    })