Reputation: 1148
I want to write a script that delete the data from all the documents of sub collection where status == expire. I have collection name user_data and this collection contain many documents all that documents contain sub collection name My_status and this My_status contains many documents, each document contains status and if status === expire than delete that data
The database structure is like this
collection - user_data
document1 - Subcollection - My_status --document1- Status expire
document2
document3
document2 - Subcollection - My_status --document1
document2--Status expire
document3
I have tried this but this does not work as I can't relate it to sub collection
// First perform the query
db.collection('user_data').where('status','==',expire).get()
.then(function(querySnapshot) {
// Once we get the results, begin a batch
var batch = db.batch();
querySnapshot.forEach(function(doc) {
// For each doc, add a delete operation to the batch
batch.delete(doc.ref);
});
// Commit the batch
return.batch.commit();
}).then(function() {
// Delete completed!
// ...
});
Upvotes: 0
Views: 1717
Reputation: 598728
Update: As of May, 2019, Cloud Firestore now supports collection group queries.
You can now query all the My_status
sub-collections:
db.collectionGroup('My_status').where('','==', 'expire').get()
.then(function(querySnapshot) {
Original Answer
What you're trying to do now is known as a "collection group query", which is not currently supported. See Firestore query subcollections
If you're trying to delete all documents from the My_status
sub-collections for all users, you will need to first loop over all users, and then query each of their subcollections:
db.collection('user_data').get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(userDocument) {
userDocument.ref.collection("My_status").where('status','==','expire').get()
.then(function(querySnapshot) {
...
Alternatively, you can store the data from all subcollections in a single global collection, and include the user ID as a field in there. That way you can query the single global collection to delete all expired documents.
Upvotes: 1