繁体   English   中英

通过Cloud Function中的时间戳从Cloud Firestore查询

[英]Query from Cloud Firestore by timestamp in Cloud Function

我编写了一个脚本,该脚本通过timestampCloud Firestore中删除事件。 Cloud Function中的链接运行的脚本。

'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
var db;
var count = 0;

exports.removeOldEvents = functions.https.onRequest(async(req, res) => {
     db = admin.firestore();
     db.collection("Events")
     .where("timeStamp", "<", new Date())
     .get().then(function(querySnapshot) {
          count = querySnapshot.size;
          querySnapshot.forEach(function(doc) {
               db.collection("Events").doc(doc.id).delete();
               if (--count == 0) {
                    console.log("Successful ");
                    res.send("Successful ");
                    res.end();
               }
          });
     }).catch(function(error) {
          console.log("Error ", error);
          res.send("Error ", error);
     });

 });

我需要一起写的东西:

new Date()

为了通过timeStamp删除旧事件?

谢谢!!!

您正在并行调用多个异步任务(即,通过delete()方法),并且仅应在所有这些任务完成后才发回响应。

由于delete()方法返回Promise,因此需要使用Promise.all() ,如下所示:

....
exports.removeOldEvents = functions.https.onRequest((req, res) => {
  db = admin.firestore();
  db.collection('Events')
    .where('timeStamp', '<', new Date())
    .get()
    .then(querySnapshot => {
      var promises = [];
      querySnapshot.forEach(doc => {
        promises.push(
          db
            .collection('Events')
            .doc(doc.id)
            .delete()
        );
      });
      return Promise.all(promises);
    })
    .then(() => {
      console.log('Successful');
      res.send('Successful');
    })
    .catch(error => {
      console.log('Error ', error);
      res.status(500).send('Error ', error);
    });
});

请注意,当您调用此HTTPS Cloud Function时, new Date().getTime()将为现在。 因此,我假设您有一些将来带有timeStamp值的文档,否则您很可能会删除整个集合!


还要注意,如果您确定查询将返回少于500个文档,则可以使用批处理write

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM