在尝试任何进一步处理之前检查用户是否存在于 Firestore 中
Check if user exists in Firestore before attempting any further processing
我在我的网站上编写了一个自定义推荐脚本,有时用户会抱怨他们的 referralId 被覆盖,因此他们失去了他们在一段时间内积累的所有积分。我想通过在尝试更新之前检查 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);
}
有没有办法让我事先检查一下?我的 table 结构如下:
要检查文档是否存在并且仅在不存在时写入,您通常会使用事务。参见 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 });
我不确定这是否适合您的用例,但一定要检查一下,因为代码比交易更简单。
我在我的网站上编写了一个自定义推荐脚本,有时用户会抱怨他们的 referralId 被覆盖,因此他们失去了他们在一段时间内积累的所有积分。我想通过在尝试更新之前检查 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);
}
有没有办法让我事先检查一下?我的 table 结构如下:
要检查文档是否存在并且仅在不存在时写入,您通常会使用事务。参见 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 });
我不确定这是否适合您的用例,但一定要检查一下,因为代码比交易更简单。