首页 > 解决方案 > 允许在 Firestore 中更新特定的嵌套值

问题描述

我需要让匿名用户能够更新嵌套架构中的特定值,而无需授予文档其余部分的权限。

events是顶级集合,我像这样更新我的文档

update(`events/${event.id}`, {
  [`boardgames.${boardgameId}.votes.${uid}`]: true,
})

我已经尝试过这个解决方案

allow update: if ((request.writeFields.size() == 1) && ('boardgames' in request.writeFields));

正如这里提到的,但它失败了(两半也独立失败)。

我错过了什么?“进入”嵌套对象时,我不是只更新一个字段吗?

能够 console.logrequestrequest.writeFields.

请注意,理想情况下,我只想允许修改最深的属性,即当前用户uidvotes.

标签: javascriptgoogle-cloud-firestorefirebase-security

解决方案


实际上,request.writeFields捕获修改字段的完整路径,因此在您的情况下,它将等于boardgames.${boardgameId}.votes.${uid}.

您可以使用带有String.matches的正则表达式

allow update: if request.auth.uid != null
  && request.writeFields.size() == 1
  && request.writeFields[0].matches("boardgames\.[^.]{5,25}\.votes\." + request.auth.uid)

小心: request.writeFields 已被弃用,但不幸的是,您的问题没有很好的替代品


推荐阅读