【问题标题】:Check if user exists in Firestore before attempting any further processing在尝试任何进一步处理之前检查用户是否存在于 Firestore
【发布时间】:2019-03-19 11:27:19
【问题描述】:

我在我的网站上编写了一个自定义推荐脚本,有时用户抱怨他们的推荐 ID 被覆盖,因此他们失去了一段时间内积累的任何积分。我想通过在尝试更新之前检查是否存在 uid 来阻止这种情况的发生。

有没有办法让我在进一步执行此命令之前检查用户的 uid 是否存在,以及是否具有有效的推荐 id?我认为问题在这里发生:

  processUser(result, firstName, lastName) {
    const referralId = this.utilService.generateRandomString(8);
    this.setUserData(result.user);
    this.setUserDetailData(result.user.uid, firstName, lastName, referralId);
    this.referralService.addUserToWaitlist(referralId);
  }

有没有办法让我事先检查一下?我的表结构如下:

【问题讨论】:

  • 我觉得你需要查询和检查

标签: javascript angular firebase google-cloud-firestore angularfire2


【解决方案1】:

要检查文档是否存在并且仅在不存在时写入,您通常会使用事务。见https://firebase.google.com/docs/firestore/manage-data/transactions#transactions。从那里:

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

        var newPopulation = sfDoc.data().population + 1;
        transaction.update(sfDocRef, { population: newPopulation });
    });
})

请注意,您还可以将用户数据与文档中的现有数据合并,以防止需要事务。例如:

userRef.set({ 
  firstName: firstName, lastName: lastName, referralId: referralId
}, { merge: true });

我不确定这是否足以满足您的用例,但请务必检查一下,因为代码比事务更简单。

【讨论】:

    猜你喜欢
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多