简体   繁体   中英

How to listen conditionally for update in a collection of room messages (firestore)?

I want to listen for collection of rooms of last 50 messages. I mean to listen for every room messages but only 50 last messages of every room.

rooms/room1/messages/message1
                    /message2
                    /message...

      room2/messages/message1
                    /message2
                    /message...

      room...

Now How can I listen to just last 50 rooms messages when the conditional_var===true and not listen when conditional_var===false . Here the conditional_var will be changed sometime.

If I understand correctly what you ask, if you "want to listen for collection of rooms of last 50 messages" you should set up a listener on a query which sort you records by creation timestamp, in descending order, and limit them to 50.

Something like the following:

var roomsListener = db.collection("rooms/room1/messages").orderBy("creationDate", "desc").limit(50)
        .onSnapshot(function(querySnapshot) {
            var docs = [];
            querySnapshot.forEach(function(doc) {
                docs.push(doc.data().anyField);
            });
            console.log("Current values: ", docs.join(", "));
        });

If you want to stop listening because conditional_var===false , just detach the listener as shown in the documentation , and as follows:

roomsListener();

Since the listener "can be cancelled by calling the function that is returned when onSnapshot is called", see https://firebase.google.com/docs/reference/js/firebase.firestore.Query#on-snapshot .


Update following your comment:

If you want to do the same but for multiple collections, just use a Collection Group query , as follows

var roomsListener = db.collectionGroup("messages").orderBy("creationDate", "desc").limit(50)
        .onSnapshot(function(querySnapshot) {
            var docs = [];
            querySnapshot.forEach(function(doc) {
                docs.push(doc.data().anyField);
            });
            console.log("Current values: ", docs.join(", "));
        });

Note that you need to create a specific index for the Collection Group query. As explained in this blog article , the first time you will trigger the listener "the client SDK will give you an error message, because the collection group index hasn't been created yet. But along with this error message there is a URL that you can follow to fix it".


To re-activate (ie re-attach) the listener, just call again onSnapshot on the query.

Here is a very simple JavaScript code with two functions that will in-turn attach or detach the listener. You should most probably make this code more robust, but it shows how you could do.

var listener = null;

function attachListener() {
    listener = db.collectionGroup("messages").orderBy("creationDate", "desc").limit(50)
        .onSnapshot(function(querySnapshot) {
            var docs = [];
            querySnapshot.forEach(function(doc) {
                docs.push(doc.data().anyField);
            });
            console.log("Current values: ", docs.join(", "));
        });
}


function detachListener() {
    if (listener != null) {
        listener();
    }
} 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM