Hi I am building some kind of voting system and I have like to prevent the same user from voting in the same post.
let db = firebase.firestore();
var postRef = db.collection("posts").doc(this.pid);
postRef.update({
votes: firebase.firestore.FieldValue.increment(1)
});
var userRef = db.collection("users").doc(this.userId);
userRef.update({
votes: firebase.firestore.FieldValue.arrayUnion(this.pid)
});
//run this line if pid is added
this.votes = this.votes + 1;
I have like to increase the vote only if pid is added to the votes array. I wonder if arrayUnion is able to provide some kind of feedback on this or anyway I can do that.
You can look at this post and you can see that the same person can vote multiple times on the same post.
Unfortunately, by design
increment
andarrayUnion
don't provide any callback.In order to implement your requirement, you need a transaction (used by both
increment
andarrayUnion
under the hood):