【问题标题】:How to delete documents in a collection with the same key value in Firebase Cloud Firestore如何在 Firebase Cloud Firestore 中删除具有相同键值的集合中的文档
【发布时间】:2020-05-23 17:47:38
【问题描述】:

我有一个集合,集合中的每个文档都有一个名为“group_id”的键。 我想删除所有分配给 group_id 的具有相同值的文档。我该怎么做?

以下是其中一份文件的屏幕截图。注意图片中的 group_id 键。

我可以删除单个文档并遍历集合,但是我无法将这两件事结合起来迭代和删除我想要删除的文档。

删除单个文档

export async function deleteCalendarEventFromFirebase(authenticatedUsersUid, id) {
    const snapshot = await firebase.firestore().collection('users').doc(authenticatedUsersUid).collection('calendar_events')
    return snapshot.doc(id).delete();
}

迭代并获得一个集合

export async function getClientCalendarEventsFromFirebase(authenticatedUsersUid,clientID) {
    const snapshot = await   firebase.firestore().collection('users').doc(authenticatedUsersUid).collection('calendar_events').where("client_id", "==", clientID).get();
        return snapshot.docs.map((val) => {
            let dataObj = val.data()
            dataObj.id = val.id;
            return dataObj
        })

    }

谢谢。

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    您需要从每个文档的删除中收集 Promise,使用 Promise.all() 将其转换为单个 Promise,并确保在删除所有文档之前最终的 Promise 不会解决。它有助于了解 DocumentSnapshot 中的所有内容。

    export async function yourFunction(authenticatedUsersUid,clientID) {
        const snapshot = await firebase.firestore()
            .collection('users')
            .doc(authenticatedUsersUid)
            .collection('calendar_events')
            .where("client_id", "==", clientID)
            .get();
    
        await Promise.all(snapshot.docs.map(doc => doc.ref.delete()));
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-22
      • 2018-08-08
      • 2021-01-08
      • 2021-11-14
      • 2021-05-09
      • 2020-09-08
      • 2018-11-01
      相关资源
      最近更新 更多