英文:
Check that a newly added field in firestore document conforms to structure
问题
I have a document in firestore consisting of a series of maps. Their field names are random UUIDs:
-6e219b89-98fb-44cd-b6ad-e22888b6fb2f
-name: 'Harry'
-age: 20
-345c635a-11cb-4165-86ef-50be50794532
-name: 'Mary'
-age: 30
I have a piece of client code which adds a new map to this document.
await updateDoc(docRef, {
[crypto.randomUUID()]: {
name: 'Sally',
age: 24,
}
});
How can I check that the newly submitted field is a map with name=string and age=number?
If I knew the field name I could write the security rule
request.resource.data.name is string;
But in this case I don't know the value of the random UUID which is the new field in the document.
英文:
I have a document in firestore consisting of a series of maps. Thier field names are random uuids:
-6e219b89-98fb-44cd-b6ad-e22888b6fb2f
-name: 'Harry'
-age: 20
-345c635a-11cb-4165-86ef-50be50794532
-name: 'Mary'
-age: 30
I have a piece of client code which adds a new map to this document.
await updateDoc(docRef, {
[crypto.randomUUID()]: {
name: 'Sally',
age: 24,
}
});
How can I check that the newly submitted field is a map with name=string and age=number?
If I knew the field name I could write the security rule
request.resource.data.name is string;
But in this case I don't know the value of the random UUID which is the new field in the document.
答案1
得分: 1
Firestore安全规则无法遍历字段(或任何其他内容)。它们必须始终确切地知道要检查哪个字段。这意味着使用当前的写操作,规则无法知道要检查哪个字段。
一个简单的解决方法是还在已知位置写入crypto.randomUUID()
的值,例如newField
:
const uuid = crypto.randomUUID()
await updateDoc(docRef, {
newField: uuid,
[uuid]: {
name: 'Sally',
age: 24,
}
});
现在,您的规则可以读取newField
以确定添加了哪个字段,然后使用该值来检查新字段是否符合您的规则。
还可以参考:
英文:
Firestore security rules cannot iterate over fields (or anything else). They must always know exactly what field to check. This means that with your current write operation, there is no way for the rules to know what field to check.
A simple workaround is to also write the crypto.randomUUID()
value in a known location, e.g. newField
:
const uuid = crypto.randomUUID()
await updateDoc(docRef, {
newField: uuid,
[uuid]: {
name: 'Sally',
age: 24,
}
});
Now your rules can read newField
to determine what field was added, and then use that value to check whether the new field adheres to your rules.
Also see:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论