D.Hodges
D.Hodges

Reputation: 2069

Is there a way to update a collectionGroup in cloud function

I'm building a chat app. When a user makes an update on their local profile I'd like to use cloud functions to make that update across a collectionGroup.

I'm successfully listening to the update in cloud functions and retrieving a list of collectionGroups with the following:

        const collectionGroupNameref = await db.collectionGroup('collectionGroupName').where('userId', '==', data.uid).get();


collectionGroupNameref.forEach(async (val: any) => {
            const connectionsRef = await db.collection('collectionGroupName').doc(val.id).get();
 
        });

But now I need to update a field within that collectionGroup and that's where I'm running into issues.

The collectionGroup is stored in 2 locations:

users{id}collectionGroupName{id}
groups{id}collectionGroupName{id}

Is it possible to update all of the documents in that collectionGroup

Upvotes: 3

Views: 2263

Answers (2)

Mehdi
Mehdi

Reputation: 2398

There is another approach you can use :

1- Get All objects in a collection group that you want to update (v1)

export const getAllItemsFromCollectionGroup = async <T>(collection: string): Promise<T[]> => {
  const items: T[] = [];
  const db = admin.firestore();
  const query = await db.collectionGroup(collection).get();
  if (query && !query.empty) {
    query.docs.forEach(doc => {
      items.push({
        ...doc.data() as T,
        id: doc.id,
        path: doc.ref.path
      });
    });
  }
  return items;
};

Note that when I can loop through returned objects, I add the absolute path to each object.

2- Now you filter your objects based on path ou subpath your are interested in.

3- Bulk update using their path

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317467

Firestore doesn't provide any methods to update an entire collection or collection group like "UPDATE WHERE" in SQL. What you are required to do instead is write each document individually. So, if you've already executed a query for documents in the collection group, can you simply iterate the documents in the result set and update each document as needed. You can use the ref property of DocumentSnapshot to easily update each document, no matter what collection contains it.

const querySnapshot = await db
    .collectionGroup('collectionGroupName')
    .where('userId', '==', 'data.uid')
    .get();
querySnapshot.docs.forEach(snapshot => {
    snapshot.ref.update(...)
})

Upvotes: 13

Related Questions