简体   繁体   English

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

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

I write a script which removes events from Cloud Firestore by timestamp . 我编写了一个脚本,该脚本通过timestampCloud Firestore中删除事件。 A script run by a link in Cloud Function . 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);
     });

 });

What I need to write together: 我需要一起写的东西:

new Date()

in order to remove old events by timeStamp? 为了通过timeStamp删除旧事件?

Thanks!!! 谢谢!!!

You are calling in parallel several asynchronous tasks (ie through the delete() method) and you should send back the response only when all these tasks are completed. 您正在并行调用多个异步任务(即,通过delete()方法),并且仅应在所有这些任务完成后才发回响应。

Since the delete() method returns a Promise, you need to use Promise.all() , as follows: 由于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);
    });
});

Note that when you will call this HTTPS Cloud Function the value of new Date().getTime() will be now. 请注意,当您调用此HTTPS Cloud Function时, new Date().getTime()将为现在。 So I make the assumption that you have some documents with a timeStamp value that is in the future, or you will most likely delete the entire collection! 因此,我假设您有一些将来带有timeStamp值的文档,否则您很可能会删除整个集合!


Also note that if you are sure your query will return less than 500 document, you could use a batched write . 还要注意,如果您确定查询将返回少于500个文档,则可以使用批处理write

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

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