You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

2 Días
3 Hrs
54 Min
3 Seg
Curso de Firebase 5 para Web

Curso de Firebase 5 para Web

Juan Guillermo Gómez Torres

Juan Guillermo Gómez Torres

Desarrollando la inserción de datos

17/32
Resources

How to configure Firestore in the constructor method?

To connect to Firestore, you must first configure your POST object. It is important that the Firestore instance is available to be used in the different functions. Therefore, we define a db variable and get the Firestore instance through:

this.db = firebase.firestore();

Next, you must define certain configurations. A key configuration is TimeStamp in snapshots, which allows you to retrieve all values stored as DayTime in TimeStamp format. To apply it:

const settings = { timestampsInSnapshots: true };this.db.settings(settings);

This setting ensures that dates are handled correctly as TimeStamp, thus optimizing the temporal data management.

How to create a Post in Firestore?

Creating a document in Firestore is a simple and dynamic process. First, you must go to the specific collection, and if it does not exist, Firestore will create it automatically. To add a document to a collection called "Post" use:

this.db.collection('Post').add({ uid: this.userUid, author: this.userEmail, title: this.postTitle, description: this.postDescription, imageLink: this.postImageLink, videoLink: this.postVideoLink, createdAt: firebase.firestore.FieldValue.serverTimestamp()}).then((ref) => { console.log('POST ID:', ref.id);}).catch((error) => { console.error('Error creating the POST', error);});

Here, each field is defined as a key:value pair in the JS object representing the document.

How to manage the storage of Date and Time?

To get the date and time from the system (server) we use firebase.firestore.FieldValue.serverTimestamp(). With this, we get Firestore to automatically handle the timestamps, which ensures that we always operate with the server time.

How to handle errors when creating a Post?

Insertion in Firestore uses promises, which makes it easy to handle errors efficiently. If something goes wrong during the creation operation, the catch block will take care of alerting about the error:

.catch((error) => { console.error('Error creating POST', error);});

This approach allows for easier debugging and effective error tracking, ensuring an uninterrupted flow in the application.

How is the Post Controller linked to user authentication?

The Post Controller is responsible for checking whether a user is authenticated before allowing the creation of a Post. This process includes:

  1. User validation: we use the firebase.auth().currentUser function to verify the current user.
const user = firebase.auth().currentUser;if (!user) { console.warn('To create a POST you must be authenticated.'); return;}
  1. Data retrieval: if the user is authenticated, their Post details and data are retrieved from the editable fields.
const title = this.titleInput.value;const description = this.descriptionInput.value;const videoLink = this.videoLinkInput.value;const imageLink = this.imageLinkInput.value;
  1. Call to the createPost function: The UID of the authenticated user and other details needed to create the Post are passed.
createPost(user.uid, user.email, title, description, imageLink, videoLink);

This ensures that only authenticated users can interact with the content creation, providing an additional level of security.

What happens after a Post is created?

Once the Post has been successfully created, the system returns a confirmation message to the user:

.then(() => { console.log('POST created successfully');})

On the other hand, in case of an error, the system will also notify appropriately, allowing developers to react effectively to possible inconveniences.

These steps ensure that the application not only works properly, but also maintains the security and integrity of the database and the user experience. Get excited to continue exploring and developing with Firestore!

Contributions 30

Questions 9

Sort by:

Want to see more contributions, questions and answers from the community?

las líneas

const settings = { timestampsInSnapshots : true} 
this.db.settings(settings)

ya no son necesarias puesto que esta configuración ya está por defecto 😄

Este es otro ejemplo de cómo se podría agregar datos

async function addUser(){
    let userData = {
        name: "Andres 2",
        lastName: "Sanabria",
        birthdate: firebase.firestore.FieldValue.serverTimestamp(),
        email: "[email protected]",
        profession: "UX/UI Designer"
    }

    let newDocID = await firebase.firestore().collection("users").add(userData).then(doc => doc.id);
    console.log("Saved: ", newDocID);
}

Un cambio de pasta térmica a los profesores no estaría mal, a lo mejor sea muy quisquilloso o parece que la computadora esta a punto de despegar 😂

creo que seria bueno actualizar este curso

Ya no es necesario hacer la configuración explicita de timestampsInSnapshots.

```const settings = { timestampsInSnapshots: true };
this.db.settings(settings);

Platzinautas, para evitar un error en post, necesitamos quitar los settings, quiten todo este codigo que les muestro 👇

La nueva actualizacion de firestore, esto lo tiene ahora como default true

timestampsInSnapshots: true // Ya es por default en firestore

Si tienen problemas de permisos para guardar en la DB, vayan a la tab de Reglas de Database y poner en true los permisos de lectura/escritura:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

Buenas, como se manejan los tipos de datos REFERENCE, que haga referencia a un documento de otra coleccion.

acabo de notar que la sesion se queda iniciada incluso despues de cerrar el navegador, como se puede evitar esto?. Si necesito que la sesión se cierre cuando se cierre el navegador

Si tienen algun error, posiblemente sea por los permisos.

La estructura json para el post fue creado desde el codigo o desde la consola?

La siguiente linea de código que es lo que retorna?

return this.db.collection('posts').add({
....
})
.then(...)
.catch(...)

Hola, tengo el siguiente problema.
Cuando registro el Post, Firestore lo almacena 2 veces.

crearPost (uid, emailUser, titulo, descripcion, imagenLink, videoLink) {
    // Indicamos a firestore que coleccion se va a emplear para añadir el documento
    // El método add, genera automáticamene el id del documento
    
    // En este caso add devuelve promesa, por tanto la retornamos para que en la sección donde se invoca
    // este metodo, se hagan tareas una vez registrados los datos
    return this.db.collection('posts').add({
      uid: uid,
      autor: emailUser,
      titulo: titulo,
      descripcion: descripcion,
      imagenLink: imagenLink,
      videoLink: videoLink,
      // En este caso le indicamos a firestore que genere la fecha actual en el servidor
      fecha: firebase.firestore.FieldValue.serverTimestamp()
    })
    .then(refDoc => {
      console.log(`Id del Post: ${refDoc.id}`)
    })
    .catch(error => {
      console.log(`Error al crear el post: ${error}`)
    })
  }
$('#btnRegistroPost').click(() => {
    // Creamos una instancia de la clase Post para registrar el documento
    const post = new Post()

    // TODO: Validar que el usuario esta autenticado
    const user = firebase.auth().currentUser
    if(user == null) {
      Materialize.toast(`Para crear el Post debes estar autenticado`, 4000)
      // Hacemos esto para que no se ejecute lo demas
      return
    }

    // Materialize.toast(`Para crear el post debes estar autenticado`, 4000)

    // Recuperar la data del formulario para crear el POST
    const titulo = $('#tituloNewPost').val()
    const descripcion = $('#descripcionNewPost').val()
    const videoLink = $('#linkVideoNewPost').val()
    const imagenLink = sessionStorage.getItem('imgNewPost') == 'null'
      ? null
      : sessionStorage.getItem('imgNewPost')

    // Invocar el método crearPost para proceder a guardarlo
    post.crearPost(user.uid, user.email, titulo, descripcion, imagenLink, videoLink)
      .then(resp => {
        // En el cuerpo del método retornamos una promise
        // Por tanto la usamos aqui para realizar tareas posteriores al registro
        Materialize.toast(`Post creado correctamente`, 4000)
        // Cerrar el modal con el form de registro de post
        $('.modal').modal('close')
      })
      .catch(err => {
        Materialize.toast(`Error => ${err}`, 4000)
      })
  })

¿Cómo se puede personalizar el modelo de autenticación?
Es decir, agregarle atributos adicionales como dirección, edad, fechaDeNacimiento, etc?

En el contructor de la clase no hace falta el siguiente codigo:

 const settings = {timestampsInSnapshots : true}
      this.db.settings(settings)

La configuracion ya se encuentra configurado por default en la version de firebase 5.8.x

Solo como un dato, Actualmente la propiedad **timestampsInSnapshots **esta deprecada. Les dejo el link a la documentación por si deseas checarlo

https://firebase.google.com/docs/reference/js/firebase.firestore.Settings.html?authuser=0#optional-timestamps-insnapshots

actualmente con la nueva version se tienen que quitar las lineas de
const settings = { timestampsInSnapshots: true }
this.db.settings(settings)
pero ahora tengo un proble que dice
onSnapshot: FirebaseError: "Missing or insufficient permissions."
alguien mas?

how to solve this error:
index.esm.js:102 [2020-03-23T18:04:21.556Z] @firebase/firestore: Firestore (7.11.0):
The timestampsInSnapshots setting now defaults to true and you no
longer need to explicitly set it. In a future release, the setting
will be removed entirely and so it is recommended that you remove it
from your firestore.settings() call now.

constructor(private afs: AngularFirestore) {
const setting = {timestampsInSnapshots: true};
this.afs.firestore.settings(setting);
}

quiero cerrar sesion en google y que se olvide de mis credenciales, pero no encuentro la manera

hola que tal… consulta… se ejecutan las consultas de insercion del lado del cliente?

Si necesitan un link pueden usar este https://www.youtube.com/watch?v=wSjEG9ARRw0

const settings = {}
this.db.settings(settings)
Puedes dejar la funcion con la configuracion vacia
@firebase/firestore: Firestore (7.23.0): The setting 'timestampsInSnapshots: true' is no longer required and should be removed.

MongoDB, are you there honey?

Increíble, me gusta porque es como usar un ORM para bases de datos relacionales, pero en este caso es nativo porque así es como la base de datos se comporta:D

Hubo un error y el corte del vídeo no me permitió ver como se soluciono, no supimos cual fue su solución

Hola, quiero integrar firestore en react nattive pero me dice que firebase.firestore() no es una funcion
si me pueden ayudar con eso se los agradeceria

Hola! en que curso aprendo a usar este tipo código?

    const imagenLink = sessionStorage.getItem('imgNewPost') == 'null'
      ? null
      : sessionStorage.getItem('imgNewPost')```

hola comunidad,
tengo una duda, en caso de que yo no quiera que los usuarios escriban dos post con el mismo nombre o titulo, como lo hago?
de antemano gracias por su ayuda.

bien