简体   繁体   English

Firebase 在插入前检查数据是否存在

[英]Firebase check data exist before insert

I was having some problem with Firebase.我在使用 Firebase 时遇到了一些问题。 What I wanted to do is create a new chatroom if it does not exist, otherwise, get the existing chatroom ID.我想做的是创建一个新的聊天室,如果它不存在,则获取现有的聊天室 ID。 What I have achieved so far is:到目前为止我所取得的成就是:

在此处输入图片说明

The database structure as such:数据库结构如下:

chatrooms 
    chatroomID
        participantID1 *(can be senderKey or recipientKey)*
        participantID2 *(can be senderKey or recipientKey)*
        latestMessage

The code where I create the new chatroom:我创建新聊天室的代码:

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);
    });

The problem is before I create the new chatroom, I need to check if both the senderKey and recipientKey existed in the same chatroom.问题是在我创建新聊天室之前,我需要检查 senderKey 和 receiverKey 是否存在于同一个聊天室中。 If both of them appeared in the same chatroom, I grab the chatroomID.如果他们都出现在同一个聊天室中,我会获取 chatroomID。 If not, then I will proceed to create a new chatroom.如果没有,那么我将继续创建一个新的聊天室。

But I have no ideas how can I actually check if both the senderKey and recipientKey appeared in the same chatroom.但我不知道如何实际检查 senderKey 和 receiverKey 是否出现在同一个聊天室中。 Any ideas?有任何想法吗?

Ps.附言。 Please ignore the latestMessage node as of now because it is meant to ease my reading purpose only.现在请忽略 latestMessage 节点,因为它只是为了减轻我的阅读目的。

Thanks!谢谢!

Well, IDK if it's a good solution, but you can create a chatroomID with both (sender and recipient ids) so you need to search in the database if exists any chatroom with both ids.好吧,IDK 如果它是一个很好的解决方案,但是您可以创建一个包含两个 ID(发件人和收件人 ID)的聊天室 ID,因此您需要在数据库中搜索是否存在具有这两个 ID 的聊天室。

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

To search in the database only once, you can sort the ids, so it'll be always the lower id first, like in the example above.要仅在数据库中搜索一次,您可以对 id 进行排序,因此它总是首先是较低的 id,就像上面的例子一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM