Daryl Wong
Daryl Wong

Reputation: 2443

Firestore break out of a query

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();

Upvotes: 0

Views: 73

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

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();
      }
    })

Upvotes: 1

Related Questions