【问题标题】:Cloud Firestore delete functionCloud Firestore 删除功能
【发布时间】:2019-07-29 00:52:38
【问题描述】:

全部,

我正在使用 Firestore 作为后端,并正在尝试编写一个将在每个月的第一天运行的云函数。此函数将需要删除该函数运行日期之前的每个数据库条目。我能够完成以下功能,但它不会删除任何条目。也许有人可以帮我解决这个问题。

export const deleteOldPrayerRequests = functions.pubsub.schedule('0 0 1 * *').onRun(async (context) => {
    const date = new Date();
    console.log('---> Timestamp', context.timestamp);
    console.log('---> Date Today', date);
    console.log('---> Date Today', date.setDate(date.getDate()));
    console.log('---> Date 14 days ago', date.setDate(date.getDate() - 14));
    const snapshot = await admin.firestore().collection('prayerRequests').get();
    snapshot.docs.forEach(doc => {
        const ts = doc.get('dateSubmitted');
        if (date.setDate(date.getDate() - 14) >= ts.toMillis()) {
            console.log(doc.data());
            doc.ref.delete().then((data: any) => {
                console.log(data);
            }).catch((error: any) => {
                console.log(error);
            });
        }
    });
});

【问题讨论】:

  • 你需要返回一个promise,当所有异步工作完成时,它会解析,否则Cloud Function会提前终止它。
  • @Doug Stevenson 你能把它作为答案发布吗?通过你得到的支持,我相信这对 OP 有帮助。

标签: javascript firebase google-cloud-firestore google-cloud-functions


【解决方案1】:

这是Firestore官方文档中提供的删除文档的示例代码sn-p。

db.collection("cities").doc("DC").delete().then(function() {
  console.log("Document successfully deleted!");
}).catch(function(error) {
  console.error("Error removing document: ", error);
});

参考Read More

【讨论】:

    【解决方案2】:

    当所有异步工作完成时,您需要返回一个解决方案 完成,否则 Cloud Function 将提前终止它。 – 道格 史蒂文森

    【讨论】:

      【解决方案3】:

      我也遇到过类似的问题。为了使删除工作,需要使用回调函数。 随着 Angular 的更新,处理它的方式似乎在不断变化。这是我使用 Angular 8 的解决方案(最新的一切):

          this.db.collection('prayerRequests')
          .get()
          .subscribe((snapshot) =>{
            snapshot.forEach(doc => {
                this.db.collection('dateSubmitted').doc(doc.id).delete()
            });
          })
      

      希望这对你有用。

      【讨论】:

        猜你喜欢
        • 2021-08-09
        • 1970-01-01
        • 1970-01-01
        • 2018-12-09
        • 2021-09-07
        • 2020-03-27
        • 2018-12-27
        • 1970-01-01
        • 2021-10-16
        相关资源
        最近更新 更多