假设我的数据库中有一个字符文档,即/characters/{characterID}
此文档的形状可以如下:
{
username: "Username",
race: "ORC or ELF",
gender: "FEMALE or MALE",
gold: 1000,
equipement: {
helmet: "null or string",
boots: "null or string"
}
}
我想允许以下用例:
username, race, gender
来为自己创建角色,这些字段不可编辑我通过使用以下规则找出了步骤1,validCreateCharacterData
验证了username, race and gender
。
service cloud.firestore {
match /databases/{database}/documents {
// Characters
match /characters/{characterID} {
allow create: if isOwner(characterID)
&& validCreateCharacterData();
}
}
}
但是我很难弄清楚如何验证其余的数据更新,因为它们可以为null或字段的各种混合。我想制定精细的规则,但是下面的方法不起作用:/
service cloud.firestore {
match /databases/{database}/documents {
// Characters
match /characters/{characterID} {
allow create: if isOwner(characterID)
&& validCreateCharacterData();
match /gold {
allow update: if request.resource.data.gold is number
}
}
}
}
答案 0 :(得分:4)
使用match
时,实际上是朝collection
/ document
方向迈出了又一步。因此update
实际上是无效的,因为它是在collection
而非document
上执行的。
您的规则应如下所示:
service cloud.firestore {
match /databases/{database}/documents {
// Characters
match /characters/{characterID} {
allow create: if isOwner(characterID)
&& validCreateCharacterData();
function isValidEquipment(val) {
return val is string
|| val == null;
}
// don't allow a write request that includes updates to username, race, or gender
allow update: if !request.writeFields.hasAny(['username','race','gender'])
&& request.resource.data.gold is number
&& isValidEquipment(request.resource.data.equipment.helmet)
&& isValidEquipment(request.resource.data.equipment.boots);
}
}
}