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();
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 executeself.addToDB()
immediately after that, without waiting for the results. You should instead do all of your conditional processing inside that callback.