【问题标题】:How to set a batch delete on creation of new document (using triggers)如何在创建新文档时设置批量删除(使用触发器)
【发布时间】:2019-11-06 00:43:19
【问题描述】:

我正在制作一个 url 更短的项目(firebase 的新手),使用带有集合 ref url/{newDocs} 的 firestore 对于每个新的文档架构如下:

let schema = {
  code: codeGeneratedbyShortidPackage,
  url: req.body.URL,
  expiredAt: Date.now()+60000  // in milisceonds i.e 10 mins for 600000
}

我的问题是,如何在 Firestore 中的上述参考中添加新文档时,为每个文档中超过其时间限制的每个文档设置批量删除。

我尝试了以下代码,但没有成功。


exports.deleteFunc = functions.firestore.document('url/{docId}').onCreate( ( change, context) => {
   
   let newbatch = db.batch() ;
   db.collection('nonauth_url').where( 'expiredAt' , '<=', Date.now()).get().then( (snapshot) => {
  snapshot.forEach( (doc) => {
     newbatch.delete(doc.ref) ;
  }) ;
   }).then( () => {
  console.log('Delete done') ;
   }) ;
   return newbatch.commit().then( () => {
  console.log('Batch Committed');
   }).catch( (err) => {
  console.error('error occurred', err) ;
   }) ;
}) ;

【问题讨论】:

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


    【解决方案1】:

    下面的代码应该可以解决问题:

    exports.deleteFunc = functions.firestore
      .document('url/{docId}')
      .onCreate((change, context) => {
        const db = admin.firestore();
        let newbatch = db.batch();
    
        return db
          .collection('nonauth_url')
          .where('expiredAt', '<=', Date.now())
          .get()
          .then(snapshot => {
            snapshot.forEach(doc => {
              newbatch.delete(doc.ref);
            });
    
            return newbatch.commit();
          })
          .catch(err => {
            console.error('error occurred', err);
          });
      });
    

    请注意,您必须在后台触发的云函数中返回 Promise 或值。我建议您观看 Firebase 视频系列中关于“JavaScript Promises”的 3 个视频:https://firebase.google.com/docs/functions/video-series/,其中解释了这一关键点。

    【讨论】:

    • 我尝试了上面的代码sn-p,但没有成功。每当我添加任何文档时,即使在等待 10-20 秒后文档仍然存在,它也不会删除旧文档。同样在 cmd 中使用 firebase serve --only hosting,firestore,functions 时有时会说未处理的承诺拒绝警告,但再次运行它,警告就会消失。
    • 我彻底测试了我的答案代码,所以它应该可以工作。当您说“每当我添加任何文档时,它都不会删除旧文档”,您会在哪个 Firestore 集合中添加文档(任何文档)?
    • 如果只在 Cloud Function 代码 (index.js) 中保留 deleteFunc 会怎样?
    • 在部署项目时deleteFunc 现在工作正常
    • "在部署项目时,deleteFunc 现在运行良好" 这到底是什么意思?你有错误吗?
    【解决方案2】:

    @renaud-tarnec 提供的云函数的Javascript版本 https://stackoverflow.com/a/56735180/9646878

    对于上述答案的 Typescript 变体

    import * as functions from 'firebase-functions';
    import * as admin from 'firebase-admin';
    import { HttpsError } from 'firebase-functions/lib/providers/https';
    admin.initializeApp(functions.config().firebase);
    
    export const onDelete = functions.firestore.document('url/{documentId}')
        .onDelete(async (snap, context) => {
    
            const docId = context.params.documentId;
    
            const db = await admin.firestore();
            const newbatch = db.batch();
    
            try {
                const someHistory = await db.collection('nonauth_url')
                                         .where('expiredAt', '<=', Date.now())
                                         .get();
                someHistory.forEach(history => {
                    newbatch.delete(history.ref);
                });
                return newbatch.commit();
            } catch (err) {
                console.error('error occurred', err);
                throw new HttpsError('internal', 'Internal Server Error');
            }
        }); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多