给定规则集,Firebase无法推送数据 [英] Firebase can't push data given the ruleset

查看:30
本文介绍了给定规则集,Firebase无法推送数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个受密码保护的聊天室,并以示例的方式找到用户的答案:

I'm trying to create a password protected chat room and found this SO answer to user as an example:

Firebase:存储会议室密码的方法

问题是,给定答案中的规则集,我不知道如何推送新数据.我的规则如下:

The problem is, given the ruleset in the answer, I can't figure out how to push new data. My rules looks like this:

{
    "rules": {
        "myApp":{
            "chatRooms" : {
                "$roomID" :  {
                    "password": {
                        ".read": "false",
                        ".write": "root.child('myApp/chatRooms/' + $roomID + 'chatInfo').child('admin').val() == auth.uid"

                    },
                    "chatInfo" : {
                        ".read":true,
                        ".write": "data.child('admin').val() === auth.uid"
                    },
                    "members" : {
                        "$user_id" : {
                            ".validate": "$user_id == auth.uid && newData.val() == root.child('feeds/chatRooms/' + $roomID + '/password').val()"
                        }
                     },
                     "messages" : {
                         ".read" : "root.child('feeds/chatRooms/' + $roomID + '/members/' + auth.uid).exists()"
                     }
                }
            }
        }
    }
}

所以现在我需要能够推送一个新的chatRoom.但是如果我这样称呼:

So now I need to be able to push a new chatRoom. But if I call this:

var obj = {
    password: "test", 
    chatInfo : {admin: this.state.currentUser.uid, chatName: "foobar"}
};
firebase.database().ref(`myApp/chatRooms`).push(obj);

它失败了,因为我没有写规则来推送到chatRooms/$ uid.如果我这样做.

It fails because I don't have write rules to push to chatRooms/$uid. If I do this.

使用这样的规则推送新数据的正确方法是什么?

What is the correct way to push new data with rules like this?

推荐答案

要使此方法有效,您必须在规则所在的地方写入路径.

For this to work you have to write to the path(s) were your rules are.

为此,您必须将 push()分为两部分:生成密钥和实际写入数据:

To do that you will have to split up your push() into two parts: generating the key and actually writing the data:

// Generate the key (this happens client side)
var key = firebase.database().ref(`myApp/chatRooms`).push().key;

// Use the key to write your data

firebase.database().ref(`myApp/chatRooms`).child(key).child('chatInfo').set({admin: this.state.currentUser.uid, chatName: "foobar"});
firebase.database().ref(`myApp/chatRooms`).child(key).child('password').set("test");

这篇关于给定规则集,Firebase无法推送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆