本文介绍了请参阅Firestore安全性中的阵列更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 reviews 集合,其中每个评论都包含一个喜欢它的用户的 uid 列表,称为 likes .模式如下:

I have a collection reviews where each review contains a list of uids of users who have liked it called likes. The schema looks like:

  • 评论(集合)
    • 标题 string
    • 作者 uid
    • 喜欢[ uid ]
    • 发布了时间戳
    • 创建了时间戳
    • 通过电子邮件发送 string

    当前,我正在处理一个喜欢评论的用户:

    Currently, I'm handling a user liking a review with:

        firebase.firestore().doc(rid).update({
          likes: firebase.firestore.FieldValue.arrayUnion(this.fetchCurrentUID())
        });
    

    不喜欢:

        firebase.firestore().doc(rid).update({
          likes: firebase.firestore.FieldValue.arrayRemove(this.fetchCurrentUID())
        });
    

    我只想让用户从喜欢" 中添加或删除自己的" uid ".

    I only want to let a user add or remove their own uid from likes.

    如何编写安全规则以确保这一点?具体来说,我需要查看列表的更新方式,例如:

    How can I write a security rule to ensure this? Specifically, I need to see how the list is being updated, for instance something like:

    let newVals = request.resource.data.new_values // or something
    return (newVals.length == 1 && newVals[0] == request.auth.uid)
    

    推荐答案

    我们可以检查最终结果,而不是检查正在更新的 arrayUnion 的值.

    Instead of checking the value of the arrayUnion we are updating with, we can check the the final result.

    request.resource.data.likes 是应用了 arrayUnion 之后的数组.

    request.resource.data.likes Is the array AFTER the arrayUnion has been applied.

    因此,喜欢应该导致request.resource.data.likes中的 request.auth.uid == true
    为了消除不喜欢,我们将其取消!((request.resource.data.likes中的request.auth.uid) == true

    Therefore liking should result in request.auth.uid in request.resource.data.likes == true
    For unliking we negate it !(request.auth.uid in request.resource.data.likes) == true

    这很容易,因为我们可以访问 request.auth.uid ,但是在无法通过这种方式访问​​假定值的情况下.以下答案有一个解决方案: Firebase安全规则,请确保一个阵列移除"仅且仅限于userId

    This is easy because we have access to request.auth.uid but in cases where we don't have the supposed value accessible this way. The following answer has a solution:Firebase security rules, ensure one "array remove" only, and only to userId

    它使用以下技巧-使用 removeAll 创建一个数组交集:

    It uses the following trick - create an array intersection with removeAll:

    resource.data.likes.removeAll(request.resource.data.likes)[0] == request.auth.uid

    这篇关于请参阅Firestore安全性中的阵列更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 04:24