0

I'm trying to update messages in firebare (context: chat functionality) like for example in the following method.

markConversationAsSeen(conversationId: string, email: string) {

    const messages = collection(this.firestore, 'messages');
    const q = query(messages,
        where('conversationId', '==' ,conversationId),
        where('to', '==' , email),
        where('seen', '==', false)
    );

    getDocs(q).then((documents) => {documents.forEach(document => {

      const docId = document.id;
      const ref = doc(this.firestore, `messages/${docId}`)

      updateDoc(ref, { seen: true }).then();
    })});
  }

I think it's not optimal what I did ! Especially since the method first looks for the messages and then it updates them one by one (multi request to firebase)

Any suggestions please to enhance it ?

Thanks !

Nicolas
  • 83
  • 1
  • 7

1 Answers1

0

May be adding async functionality could improve performance something like this:

import { collection, query, where, getDocs, updateDoc, doc } from "firebase/firestore";
import { db } from './firebase.js';
async function mark(conversationId, email) {

    const messages = collection(db, 'messages');
    const q = query(messages,
        where('conversationId', '==' ,conversationId),
        where('to', '==' , email),
        where('seen', '==', false)
    );

    const querySnapshot = await getDocs(q);

    querySnapshot.forEach((document) => {
      const docId = document.id;
      console.log(docId);
      const ref = doc(db, `messages/${docId}`)
      updateDoc(ref, { seen: true });
    });
  }

May be using batch will also improve the query performance as shown in this thread.

Have a look on official doc

Rohit Kharche
  • 2,541
  • 1
  • 2
  • 13