【问题标题】:Delete data from all the documents of sub collection with where condition in firestore在firestore中使用where条件从子集合的所有文档中删除数据
【发布时间】:2019-03-18 08:24:48
【问题描述】:

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

数据库结构是这样的

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

【问题讨论】:

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


    【解决方案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 作为字段包含在其中。这样您就可以查询单个全局集合以删除所有过期的文档。

    【讨论】:

      猜你喜欢
      • 2018-11-01
      • 2018-10-19
      • 1970-01-01
      • 2020-09-08
      • 2018-07-20
      • 1970-01-01
      • 2020-09-17
      相关资源
      最近更新 更多