更新时间:2023-02-05 17:59:13
通过使用电子邮件地址作为关键字,您可以确保每个电子邮件地址只有一个条目:
By using the email address as a key, you can make sure there will be only one entry for each email address:
var fbRef = new Firebase('https://someurl.firebaseio.com/');
// create a new user somehow
var newUser = {
fullName: "John Doe",
company: "Pet's Place",
email: "john@petsplace.org"
}
// escape '.' because it can not be used as a key in FB
function escapeEmail(email){
return email.replace(/\./g, ',');
}
fbRef.child('accounts').child(escapeEmail(newUser.email)).set(newUser, function(err) {
if(err) {
// if there was an error, the email address already exists
}
);
然后在您的规则中验证密钥(电子邮件地址)不存在:
Then in your rules validate that the key (email address) does not already exist:
{
"rules": {
".read": true,
"accounts": {
"$account": {
".write": true,
".validate": "!root.child('accounts').child(newData.child('email').val().replace(/\./g, ',')).exists()"
}
}
}
}
另请查看此处以获取更多信息:什么 Firebase 规则将防止基于其他字段的集合中的重复项?和这里:如何防止 Firebase 中出现重复的用户属性?
Also have a look here for some additional information: What Firebase rule will prevent duplicates in a collection based on other fields? and here: How do you prevent duplicate user properties in Firebase?