3

How can I add a future date and time to a firestore document and add a function when that time expires? For example today I create a document and record that time and then I want to register that fifteen days later the publicado field will be false. It's possible?

I am creating a document in firestore in the following way:

component.ts

import { Component, OnInit } from '@angular/core';
import { FirebaseService } from '../../../services/firebase.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

forma: FormGroup;

constructor( fb: FormBuilder, private fs: FirebaseService ) {
  this.forma = fb.group ({
    fechaCreacion: [ firebase.firestore.FieldValue.serverTimestamp() ],
    publicado: [ true ],
  })
}

agregarAviso() {
  this.fs.addAviso(this.forma.value);
}

firebase.service.ts

constructor( private afs: AngularFirestore ) {}

addAviso(aviso){
  this.afs.collection('avisos').add(aviso);
}

As a result I get the following: enter image description here

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Paco Zevallos
  • 2,165
  • 7
  • 30
  • 68

1 Answers1

4

Firestore doesn't have a concept of a TTL (time to live) for documents. Documents exist forever until some code directly deletes them.

You could write some code to periodically query for documents that should be expired, and you will have to accept that they may finally be deleted after the timestamp, by up to the amount of time your process runs periodically. You will likely want to run this on a backend you control, with a scheduler that you control, using the Firebase Admin SDK.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Okay. I think I have not raised my approach well. What I try is not to delete the document but rather to update it. So for example is it possible to update the `published` field to` false` after some time? This is what I do now to update it at that moment: html `(ngModelChange) =" updatePublicated (warning.id, warning, $ event)"` ts: `updatePublicated (key, obj, e) {      this.fs.updatePosted (key, e);    }` – Paco Zevallos Jun 29 '18 at 02:03
  • service: `updatePublicated (key, published) {      this.afs.doc ('warnings /' + key) .update ({published});    } – Paco Zevallos Jun 29 '18 at 02:04
  • There is no scheduled work at all in Firestore. You still have to do what I'm suggesting in my answer. – Doug Stevenson Jun 29 '18 at 02:21