0
votes

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]
      })
    }
})
1

1 Answers

0
votes

There might be many solution I think. First you can check if reverse document exists, however in my opinion it's not very convenient.

I would create conversations document ids without relation to users, but add users field with array of users to every document.

Than you can do array membership queries like:

db.collection("conversations").where("users","array-contains", chatuser.uid);

for checking if one or both users are already in any document.