user1088984
user1088984

Reputation: 37

Firebase doc changes

thanks for your help, I am new to firebase, I am designing an application with Node.js, what I want is that every time it detects changes in a document, a function is invoked that creates or updates the file system according to the new structure of data in the firebase document, everything works fine but the problem I have is that if the document is updated with 2 or more attributes the makeBotFileSystem function is invoked the same number of times which brings me problems since this can give me performance problems or file overwriting problems since what I do is generate or update multiple files.

I would like to see how the change can be expected but wait until all the information in the document is finished updating, not attribute by attribute, is there any way? this is my code:

let botRef = firebasebotservice.db.collection('bot');
    botRef.onSnapshot(querySnapshot => {
        querySnapshot.docChanges().forEach(change => {
            if (change.type === 'modified') {
                console.log('bot-changes ' + change.doc.id);
                const botData = change.doc.data();
                botData.botId = change.doc.id;
                //HERE I CREATE OR UPDATE FILESYSTEM STRUCTURE, ACCORDING Data changes
                fsbotservice.makeBotFileSystem(botData);
            }
        });
    });

Upvotes: 0

Views: 780

Answers (2)

Fabricio Espinoza
Fabricio Espinoza

Reputation: 463

You should use docChanges() method like this:

    db.collection("cities").onSnapshot(querySnapshot => {

        let changes = querySnapshot.docChanges();
        for (let change of changes) {
            var data = change.doc.data();
            console.log(data);
        }


    });

Upvotes: 0

Happy-Monad
Happy-Monad

Reputation: 2002

The onSnapshot function will notify you anytime a document changes. If property changes are commited one by one instead of updating the document all at once, then you will receive multiple snapshots.

One way to partially solve the multiple snapshot thing would be to change the code that updates the document to commit all property changes in a single operation so that you only receive one snapshot.

Nonetheless, you should design the function triggered by the snapshot so that it can handle multiple document changes without breaking. Given that document updates will happen no matter if by single/multiple property changes your code should be able to handle those. IMHO the problem is the filesystem update rather than how many snaphots are received

Upvotes: 1

Related Questions