【问题标题】:Angularfire Increment transactionAngularfire增量事务
【发布时间】:2018-09-03 18:18:37
【问题描述】:

我无法增加帖子“赞”的计数。以下是我现在拥有的:

addLike(pid, uid) {
    const data = {
      uid: uid,
    };
    this.afs.doc('posts/' + pid + '/likes/' + uid).set(data)
 .then(() => console.log('post ', pid, ' liked by user ', uid));

  const totalLikes = {
         count : 0 
        };
        const likeRef = this.afs.collection('posts').doc(pid);
         .query.ref.transaction((count => {
           if (count === null) {
               return count = 1;
            } else {
               return count + 1;
            }
        }))
        }

这显然会抛出错误。

我的目标是“喜欢”一个帖子并在另一个位置增加一个“计数器”。可能作为每个 Pid 的一个字段?

我在这里缺少什么?我确定我的路径是正确的..

提前致谢

【问题讨论】:

  • 错误是什么?

标签: javascript firebase google-cloud-firestore angularfire5


【解决方案1】:

您将使用 Firebase 实时数据库 API 处理 Cloud Firestore 上的事务。虽然这两个数据库都是 Firebase 的一部分,但它们完全不同,您不能使用另一个数据库的 API。

要详细了解如何在 Cloud Firestore 上运行事务,请参阅文档中的 updating data with transactions

它看起来像这样:

return db.runTransaction(function(transaction) {
    // This code may get re-run multiple times if there are conflicts.
    return transaction.get(likeRef).then(function(likeDoc) {
        if (!likeDoc.exists) {
            throw "Document does not exist!";
        }

        var newCount = (likeDoc.data().count || 0) + 1;
        transaction.update(likeDoc, { count: newCount });
    });
}).then(function() {
    console.log("Transaction successfully committed!");
}).catch(function(error) {
    console.log("Transaction failed: ", error);
});

【讨论】:

  • 好的,我知道你要去哪里了。但是,我收到错误“ReferenceError:找不到变量:db”。有什么想法吗?
  • 这只是对 Firebase 的引用,通常使用 var db = firebase.firestore(); 之类的东西进行初始化。 Firebase 文档中的 Get started 对此进行了介绍。
猜你喜欢
  • 2022-08-19
  • 1970-01-01
  • 1970-01-01
  • 2021-02-15
  • 2021-12-01
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 2018-05-01
相关资源
最近更新 更多