我在我的网站上编写了一个自定义推荐脚本,有时用户会提示他们的推介 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);
}
有没有办法让我事先检查一下?我的表结构如下:
最佳答案
要检查文档是否存在并仅在不存在时写入,您通常会使用事务。请参阅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/