【问题标题】:Firestore arrayunion provides any callback?Firestore arrayunion 提供任何回调?
【发布时间】:2021-01-18 18:06:50
【问题描述】:

您好,我正在构建某种投票系统,我想防止同一用户在同一个帖子中投票。

  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 是否能够对此提供某种反馈,或者无论如何我可以做到。

您可以查看this post,您可以看到同一个人可以对同一个帖子进行多次投票。

【问题讨论】:

    标签: javascript firebase vue.js google-cloud-firestore nuxtjs


    【解决方案1】:

    不幸的是,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]});
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 2020-11-26
      • 2019-02-09
      • 2019-04-14
      • 1970-01-01
      • 2019-09-05
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多