我正在尝试创建一个受密码保护的聊天室,并以示例的方式找到用户的答案:
Firebase: approach to storing room passwords
问题是,给定答案中的规则集,我不知道如何推送新数据。我的规则如下:
{
"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。但是如果我这样称呼:
var obj = {
password: "test",
chatInfo : {admin: this.state.currentUser.uid, chatName: "foobar"}
};
firebase.database().ref(`myApp/chatRooms`).push(obj);
它失败了,因为我没有写规则来推送到chatRooms / $ uid。如果我这样做。
用这样的规则推送新数据的正确方法是什么?
答案 0 :(得分:1)
要执行此操作,必须将规则写入路径。
为此,您必须将push()
分成两部分:生成密钥和实际写入数据:
// 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");