首页 > 解决方案 > 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 是否能够对此提供某种反馈,或者无论如何我可以做到这一点。

你可以看看这个帖子,你可以看到同一个人可以在同一个帖子上多次投票。

标签: javascriptfirebasevue.jsgoogle-cloud-firestorenuxtjs

解决方案


不幸的是,按照设计incrementarrayUnion不提供任何回调。

为了实现您的要求,您需要一个事务在后台使用):incrementarrayUnion

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

推荐阅读