Home > other >  How to get docs for non-currentUsers in Firebase and Vue
How to get docs for non-currentUsers in Firebase and Vue

Time:09-04

I am attempting to built a chat app with Vue, Firebase Firestore and Firebase authentication. After registering a user, logging in, and submitting a message, I am using the getMessage function below to retrieve the messages from a collection assigned to a doc for the currently logged-in user.

const messages = ref([])

const getMessages = () => {
firebase.firestore().collection("users").doc(firebase.auth().currentUser.uid).collection('messages').orderBy('timestamp')
      .onSnapshot(snap => {
        messages.value = []
        snap.forEach(doc => {
          var msg = doc.data();
          msg.id = doc.id;
          messages.value.push(msg)
        })
      }) 
    },

However, I have multiple registered users and am wanting to retrieve messages for all the users, not just the currentUser. How can I set up the above firestore collection method chain to retrieve messages for all of the registered users, not just currentUser?

CodePudding user response:

You can use Collection Group query here that'll fetch messages from all users as per your use case.

const messages = ref([])

const getMessages = () => {
  firebase.firestore().collectionGroup("messages").orderBy('timestamp')
    .onSnapshot(snap => {
      const messages = snap.docs.map((doc) => ({
        messageId: doc.id,
        userId: doc.parent.parent.id,
        ...doc.data()
      }))

      messages.value = messages
    })
}

Do make sure your security allow users to add message to their sub-collection only but let everyone read them. For example,

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{userId=**}/messages/{messageId} {
      allow read: if request.auth == userId; 
    }
 
    match /users/{userId}/messages/{messageId} { 
      allow write: if request.auth.uid == userId;
    }
  }
}

Checkout the documentation for more information about security rules.

  • Related