javascript - Firestore arrayunion 提供任何回调?
问题描述
嗨,我正在构建某种投票系统,我想防止同一个用户在同一个帖子中投票。
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;
只有在将 pid 添加到投票数组时,我才想增加投票。我想知道 arrayUnion 是否能够对此提供某种反馈,或者无论如何我可以做到这一点。
你可以看看这个帖子,你可以看到同一个人可以在同一个帖子上多次投票。
解决方案
不幸的是,按照设计increment
,arrayUnion
不提供任何回调。
为了实现您的要求,您需要一个事务(在后台使用):increment
arrayUnion
const postRef = db.collection("posts").doc(this.pid);
const userRef = db.collection("users").doc(this.userId);
db.runTransaction(async (t) => {
const post = await t.get(postRef);
const user = await t.get(userRef);
if (!user.get('votes').includes(this.pid)) {
t.update(postRef, {votes: post.get('votes') + 1});
t.update(userRef, {votes: [...user.get('votes'), this.pid]});
}
});
推荐阅读
- android - 创建 TeamSite 混合应用程序 16
- angular - Angular 6 通过 json 并根据 id 获取数据
- javascript - ASP.net 在客户端上下文中运行 javascript
- javascript - 如何选择调用ngIf的函数?
- c++ - ja 用于有符号数而不是 jg
- r - 将特定文本粘贴到没有它的字符串
- python-3.x - Aruco OpenCV 示例,所有标记都被拒绝
- r - 如果抛出错误则延迟函数:try_catch 和 if else
- excel - 来自多个工作表的自动求和
- phpmailer - phpmailer 将内联图像作为附件发送