I was having some problem with Firebase. What I wanted to do is create a new chatroom if it does not exist, otherwise, get the existing chatroom 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. If both of them appeared in the same chatroom, I grab the 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. Any ideas?
Ps. Please ignore the latestMessage node as of now because it is meant to ease my reading purpose only.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.