Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 插入前存在Firebase检查数据_Javascript_Firebase_Firebase Realtime Database - Fatal编程技术网

Javascript 插入前存在Firebase检查数据

Javascript 插入前存在Firebase检查数据,javascript,firebase,firebase-realtime-database,Javascript,Firebase,Firebase Realtime Database,我在Firebase上遇到了一些问题。如果聊天室不存在,我想做的是创建一个新的聊天室,否则,获取现有的聊天室ID。到目前为止,我取得的成果是: 数据库结构如下所示: chatrooms chatroomID participantID1 *(can be senderKey or recipientKey)* participantID2 *(can be senderKey or recipientKey)* latestMessag

我在Firebase上遇到了一些问题。如果聊天室不存在,我想做的是创建一个新的聊天室,否则,获取现有的聊天室ID。到目前为止,我取得的成果是:

数据库结构如下所示:

chatrooms 
    chatroomID
        participantID1 *(can be senderKey or recipientKey)*
        participantID2 *(can be senderKey or recipientKey)*
        latestMessage
创建新聊天室的代码:

let promiseRoomKey = new Promise((resolve, reject) => {
        // need to perform check before insert new chatroom

        // create room for chat
        var roomKey = firebase.database().ref('chatrooms').push({
            [senderKey]: true,
            [recipientKey] : true
        }).getKey();

    resolve(roomKey);
    });
问题是在创建新聊天室之前,我需要检查senderKey和recipientKey是否都存在于同一聊天室中。如果他们两个出现在同一个聊天室,我会抓住聊天室的ID。如果没有,那么我将继续创建一个新的聊天室

但我不知道如何才能真正检查senderKey和recipientKey是否出现在同一聊天室中。有什么想法吗

请忽略最新消息节点,因为它只是为了方便我阅读


谢谢

好吧,IDK是一个好的解决方案,但您可以同时创建一个聊天室ID(发送者ID和接收者ID),因此您需要在数据库中搜索是否存在同时具有这两个ID的聊天室

users
  id001:"User Name"
  id002:"User Name"
chatrooms
  id001id002
    id001
    id002
    latestMessage

要仅在数据库中搜索一次,您可以对id进行排序,因此它将始终首先是较低的id,如上面的示例所示。

使用firebase事务,您可以在继续操作之前检查数据库中的当前值。请参阅当您希望确保某个值或值的组合是唯一的时,请参阅是否可以将该值/这些值放入键中。由于密钥在其集合中保证是唯一的,所以一半的问题会自动解决。在这种情况下,您可以根据聊天室参与者的ID确定聊天室ID。我明白了,我明白了。但是我如何才能将连接的字符串作为聊天室ID推送呢?因为在firebase中使用push()会自动生成一个唯一的推ID,对吗?另外,通过将参与者ID设置为聊天室ID,是更好地设置其唯一的推送帐户ID还是仅设置用户名本身?而不是调用
ref.push(…)
使用
ref.child(key)。设置(…)
。抱歉,您的意思是通过同时设置两个用户ID来创建聊天室ID?另外,在连接字符串之后,如何实际检查房间是否存在?是的,只需连接它们。要检查,只需使用
firebase.database().ref('chattrooms/id001id002')。一次('value')。然后((snapshot)=>{//检查snapshot.val()是否存在})