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
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