[英]Delete data from all the documents of sub collection with where condition in firestore
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
我有集合名称user_data,此集合包含许多文档,所有这些文档包含子集合名称My_status,并且此My_status包含许多文档,每个文档包含状态,如果status === expired则删除该数据
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!
// ...
});
Update: As of May, 2019, Cloud Firestore now supports collection group queries . 更新:自2019年5月起,Cloud Firestore现在支持收藏组查询 。
You can now query all the My_status
sub-collections: 现在,您可以查询所有
My_status
子集合:
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
请参阅Firestore查询子集合
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: 如果要为所有用户从
My_status
子集合中删除所有文档,则需要首先遍历所有用户,然后查询其每个子集合:
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. 或者,您可以将来自所有子集合的数据存储在单个全局集合中,并将用户ID包括在其中作为字段。 That way you can query the single global collection to delete all expired documents.
这样,您可以查询单个全局集合以删除所有过期的文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.