检查Firestore文档中新添加的字段是否符合结构。

huangapple go评论64阅读模式
英文:

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:

huangapple
  • 本文由 发表于 2023年5月21日 02:19:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76296752.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定