简体   繁体   中英

Google Cloud Function delete Firestore document

I tested my javascript on local emulator. There are 2 actions, if Timestamp is over 7 days delete the document (this is working like a charm <3) but the else is he should check the "img" its a normal url if this return 404 then delete like on the first action, this is ONLY working on local emulator, when i deploy it to Cloud function its not working anymore and just says eg "Function execution took 7957 ms, finished with status: 'ok'" BUT on local it works as expected.

exports.removeExpiredDocuments = functions.region('europe-west1').runWith({ memory: "256MB" }).pubsub.schedule("every 1 hours").onRun(async (context) => {
    const db = admin.firestore();
    const now = firestore.Timestamp.now();
    const ts = firestore.Timestamp.fromMillis(now.toMillis() - 604800000); // 168 hours in milliseconds = 604800000

    const snaps = await db.collection("products").get();
    let promises = [];
    snaps.forEach((snap) => {
        // functions.logger.info("forEachSnap");
        if (snap.data().created_time < ts) {
            promises.push(snap.ref.delete());
            functions.logger.info('[Time] older than 7 Days ' + snap.data().name, { structuredData: true });
        } else {
            requesth(snap.data().img, function (error, response) {
                functions.logger.info('[img] error: ' + error, { structuredData: true });
                if (response.statusCode == 404) {
                    promises.push(snap.ref.delete());
                    functions.logger.info('[img] not found ' + snap.data().name, { structuredData: true });
                }
            });
        }
    });

    return Promise.all(promises);
});

Working on local emulator (with same url as in firebase) and i expect that its working on cloud aswell

firestore.Timestamp.now() does not return a value that can be correctly compared to other Timestamps with < and > comparisons. That means this line of code doesn't do what you think:

if (snap.data().created_time < ts)

If you want to compare two Timestamp objects with each other, you must take another approach. One way is to convert them both to milliseconds with toMillis() and compare those integers with each other. Or convert them to Date and compare them with the appropriate object method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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