javascript - 在尝试任何进一步处理之前检查用户是否存在于 Firestore 中

标签 javascript angular firebase google-cloud-firestore angularfire2

我在我的网站上编写了一个自定义推荐脚本,有时用户会提示他们的推介 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);
  }

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

enter image description here

最佳答案

要检查文档是否存在并仅在不存在时写入,您通常会使用事务。请参阅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 });

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

关于javascript - 在尝试任何进一步处理之前检查用户是否存在于 Firestore 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55239930/

相关文章:

javascript - 在 useEffect 的依赖数组中使用比较

javascript - 停止逐个滚动到每个单击的链接,仅滚动到第一个单击的链接

javascript - React.js 引用没有出现在对象内部

javascript - 通过 webpack 包含 socket.io 时获取 `Uncaught ReferenceError: io is not defined`

angular - 显示访客的注册/登录链接,登录时隐藏?

Angular 2 : 404 error occur when I refresh through the browser

没有 cocoapods 的 iOS firebase Mach-O 链接器错误

node.js - 在本地运行 Node test.js 时访问本地 Firebase 环境变量

javascript - Angular:仅对 html 表单的某些部分启用表单输入

javascript - 在 JavaScript 中从 Firebase 数据库检索数据