从条件在Firestore中的子集合的所有子文档中删除数据

时间:2018-10-13 07:56:00

标签: node.js database firebase google-cloud-firestore

我想编写一个脚本,从状态==过期的子集合的所有文档中删除数据。 我有集合名称user_data,并且此集合包含许多文档,所有这些文档都包含子集合名称My_status,并且这个My_status包含许多文档,每个文档包含状态,并且如果status === expired则删除该数据

数据库结构是这样的

collection - user_data
                     document1 - Subcollection - My_status --document1- Status expire      
                                                             document2 
                                                             document3

                     document2 - Subcollection - My_status --document1 
                                                             document2--Status expire
                                                             document3

我已经尝试过了,但这无法正常工作,因为我无法将其与子集合相关

// 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!
  // ...
}); 

1 个答案:

答案 0 :(得分:1)

更新:自2019年5月起,Cloud Firestore现在支持collection group queries

您现在可以查询所有My_status子集合:

db.collectionGroup('My_status').where('','==', 'expire').get()
.then(function(querySnapshot) {

原始答案

您现在要执行的操作称为“收集组查询”,目前不支持。参见Firestore query 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) {
      ...

或者,您可以将所有子集合中的数据存储在单个全局集合中,并将用户ID包括在其中作为字段。这样,您可以查询单个全局集合以删除所有过期的文档。