Tsabary
Tsabary

Reputation: 3928

Can I change in Firestore all documents in who correspond to a certain condition without querying for all of them first?

I am building some sort of a social network. To save read operations, for every post, I store the details of the author's details with it (image and name). I am trying to create a cloud function that when a user edits their profile details, the function will change all the posts the user has wrote and update them accordingly (with the new name/image).

The problem I am facing (not much of a problem, just trying to be efficient), is how do I edit all the posts by that user? Do I have to query for all the posts by that user first and then loop through the results to change them? Or is there some method that would allow me to edit all documents that follow a certain condition?

This is my function right now, and I placed inside the hypothetical function I hope exists.

exports.updateUser = functions.firestore.document('communities_data/{community}/profiles/{profileID}').onUpdate((change, context) => {
    // Retrieve the current and previous value
    const data = change.after.data();
    const previousData = change.before.data();

    // We'll only update if the name has changed.
    // This is crucial to prevent infinite loops.
    if (data !== undefined && previousData !== undefined) {

        if (data.name !== previousData.name || data.image !== previousData.image) {

           //I am looking for something like this
            return db.doc('communities_data/' + context.params.community + '/questions').where('author_ID', '==', context.params.profileID).set

        } else {
            return null;
        }
    } else {
        return null;
    }
});

Upvotes: 0

Views: 28

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317362

With Cloud Firestore, there is no bulk update mechanism like SQL "update where". You have to query for the documents you want to update, iterate the results, and update them each individually.

Upvotes: 1

Related Questions