我在使用 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 是否出现在同一个聊天室中。有什么想法吗?
附言。请忽略 latestMessage 节点,因为它只是为了方便我阅读。
谢谢!
最佳答案
好吧,IDK 如果它是一个很好的解决方案,但您可以创建一个同时具有(发件人和收件人 ID)的聊天室 ID,因此您需要在数据库中搜索是否存在具有这两个 ID 的任何聊天室。
users
id001:"User Name"
id002:"User Name"
chatrooms
id001id002
id001
id002
latestMessage
要仅在数据库中搜索一次,您可以对 ID 进行排序,因此它始终是较低的 ID,如上例所示。
关于javascript - 插入前 Firebase 检查数据是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47973806/