So I'm building a chat app and have run into a problem, which is as follows: When a user sends a message, firestore creates a document with an id of the currentuser uid and the chat users uid. So for example,
db.collection('conversations').doc(currentuser.uid+chatuser.uid)
But the problem with this is that when the chatuser, the one who will respond to this message on his account, he will now be the current user and therefore a new doccument will have been created simply because the uids are now in reverse. Therefore, is there anyway to verify that as long as the doc id contains both the users uids, the order in which they appear is irrelevant?
I am trying to do it something like this, but whenever i send a message, it automatically creates a new document. Any suggestions?
let usersref = db.collection('conversations')
let query = usersref.where('users','array-contains', [userAuth.uid,
chatuser.uid])
let newref = db.collection('conversations').doc()
function sendMsg(){
let msgobject = {
userUid1: userAuth.uid,
userUid2: chatuser.uid,
msg: msg.replaceAll(' ',''),
date: firebase.firestore.Timestamp.now(),
viewed: false
}
if(msg.replace(/\s/g, '').length){
query.get().then(docsnapshot=>{
if(docsnapshot.exists){
query.update({
msgs: firebase.firestore.FieldValue.arrayUnion(msgobject),
convoinfo: {
userUid1: userAuth.uid,
userUid2: chatuser.uid,
convoid:convoid,
typing: false
},
users: [userAuth.uid, chatuser.uid]
})
}else {
newref.set({
msgs: firebase.firestore.FieldValue.arrayUnion(msgobject),
convoinfo: {
userUid1: userAuth.uid,
userUid2: chatuser.uid,
convoid:convoid,
typing: false
},
users: [userAuth.uid, chatuser.uid]
})
}
})