database package

Base de datos en tiempo real de Firebase

Funciones

Función Descripción
función (aplicación...)
getDatabase(aplicación, URL) Devuelve la instancia del SDK de Realtime Database que está asociado con la FirebaseApp proporcionada. . Inicializa una nueva instancia con la configuración predeterminada si no existe ninguna instancia o si la instancia existente usa una URL de base de datos personalizada.
función(bd...)
connectDatabaseEmulator (db, host, puerto, opciones) Modifique la instancia proporcionada para comunicarse con el emulador de Realtime Database.

Nota: Este método debe llamarse antes de realizar cualquier otra operación.

ir sin conexión (db) Se desconecta del servidor (todas las operaciones de la base de datos se completarán sin conexión). El cliente mantiene automáticamente una conexión persistente con el servidor de la base de datos, que permanecerá activo indefinidamente y se volverá a conectar cuando se desconecte. Sin embargo, los métodos goOffline() y goOnline() pueden usarse para controlar la conexión del cliente en los casos en que no se desea una conexión persistente. Mientras esté fuera de línea, el cliente ya no recibirá actualizaciones de datos de la base de datos. Sin embargo, todas las operaciones de la base de datos realizadas localmente continuarán activando eventos de inmediato, lo que permitirá que su aplicación continúe comportándose normalmente. Además, cada operación realizada localmente se pondrá en cola automáticamente y se volverá a intentar al volver a conectarse al servidor de la base de datos. Para volver a conectarse a la base de datos y comenzar a recibir eventos remotos, consulte goOnline() .
ir en línea (db) Vuelve a conectarse al servidor y sincroniza el estado de la base de datos fuera de línea con el estado del servidor. Este método debe usarse después de deshabilitar la conexión activa con goOffline() . Una vez reconectado, el cliente transmitirá los datos apropiados y activará los eventos apropiados para que su cliente "se ponga al día" automáticamente.
ref(bd, ruta) Devuelve una Reference que representa la ubicación en la base de datos correspondiente a la ruta proporcionada. Si no se proporciona una ruta, la Reference apuntará a la raíz de la base de datos.
referenciaDeURL(bd, url) Devuelve una Reference que representa la ubicación en la base de datos correspondiente a la URL de Firebase proporcionada. Se lanza una excepción si la URL no es una URL válida de la base de datos de Firebase o si tiene un dominio diferente al de la instancia Database actual. Tenga en cuenta que todos los parámetros de consulta ( orderBy , limitToLast , etc.) se ignoran y no se aplican a la Reference devuelta.
función()
forzarEncuestaLarga() Fuerce el uso de longPolling en lugar de websockets. Esto se ignorará si se utiliza el protocolo websocket en la URL de la base de datos.
fuerzaWebSockets() Forzar el uso de websockets en lugar de longPolling.
ordenarPorClave() Crea una nueva QueryConstraint que ordena por clave. Ordena los resultados de una consulta por sus valores clave (ascendentes). Puede leer más sobre orderByKey() en Ordenar datos .
orden por prioridad () Crea una nueva QueryConstraint que ordena por prioridad. Las aplicaciones no necesitan usar prioridad, pero pueden ordenar colecciones por propiedades ordinarias (consulte Ordenar datos para conocer alternativas a la prioridad.
ordenarPorValor() Crea una nueva QueryConstraint que ordena por valor. Si los elementos secundarios de una consulta son todos valores escalares (cadena, número o booleano), puede ordenar los resultados por sus valores (ascendentes). Puede leer más sobre orderByValue() en Ordenar datos .
servidorTimestamp() Devuelve un valor de marcador de posición para completar automáticamente la marca de tiempo actual (tiempo desde la época de Unix, en milisegundos) según lo determinado por los servidores de Firebase.
función(delta...)
incremento (delta) Devuelve un valor de marcador de posición que se puede usar para incrementar atómicamente el valor actual de la base de datos en el delta proporcionado.
función (habilitada...)
enableLogging(habilitado, persistente) Registra información de depuración en la consola.
función(límite...)
limitToFirst(límite) Crea una nueva QueryConstraint que, si se limita al primer número específico de elementos secundarios. El método limitToFirst() se utiliza para establecer un número máximo de elementos secundarios que se sincronizarán para una devolución de llamada determinada. Si establecemos un límite de 100, inicialmente solo recibiremos hasta 100 eventos child_added . Si tenemos menos de 100 mensajes almacenados en nuestra base de datos, se activará un evento child_added para cada mensaje. Sin embargo, si tenemos más de 100 mensajes, solo recibiremos un evento child_added para los primeros 100 mensajes pedidos. A medida que cambien los elementos, recibiremos eventos child_removed por cada elemento que se elimine de la lista activa para que el número total se mantenga en 100. Puede leer más sobre limitToFirst() en Filtrado de datos .
limitToLast(límite) Crea una nueva QueryConstraint que se limita a devolver solo el último número especificado de elementos secundarios. El método limitToLast() se utiliza para establecer un número máximo de elementos secundarios que se sincronizarán para una devolución de llamada determinada. Si establecemos un límite de 100, inicialmente solo recibiremos hasta 100 eventos child_added . Si tenemos menos de 100 mensajes almacenados en nuestra base de datos, se activará un evento child_added para cada mensaje. Sin embargo, si tenemos más de 100 mensajes, solo recibiremos un evento child_added para los últimos 100 mensajes pedidos. A medida que cambien los elementos, recibiremos eventos child_removed por cada elemento que se elimine de la lista activa para que el número total se mantenga en 100. Puede leer más sobre limitToLast() en Filtrado de datos .
función (registrador...)
enableLogging(registrador) Registra información de depuración en la consola.
función (padre...)
niño (padre, ruta) Obtiene una Reference para la ubicación en la ruta relativa especificada. La ruta relativa puede ser un nombre secundario simple (por ejemplo, "ada") o una ruta más profunda separada por barras (por ejemplo, "ada/nombre/nombre").
empujar (padre, valor) Genera una nueva ubicación secundaria usando una clave única y devuelve su Reference . Este es el patrón más común para agregar datos a una colección de elementos. Si proporciona un valor a push() , el valor se escribe en la ubicación generada. Si no pasa un valor, no se escribe nada en la base de datos y el elemento secundario permanece vacío (pero puede usar la Reference en otro lugar). Las claves únicas generadas por push() se ordenan según la hora actual, por lo que la lista de elementos resultante se ordena cronológicamente. Las claves también están diseñadas para ser imposibles de adivinar (contienen 72 bits aleatorios de entropía). Ver Agregar a una lista de datos . Consulte las 2^120 formas de garantizar identificadores únicos .
función (ruta...)
orderByChild(ruta) Crea una nueva QueryConstraint que ordena por la clave secundaria especificada. Las consultas solo pueden ordenarse por una clave a la vez. Llamar a orderByChild() varias veces en la misma consulta es un error. Las consultas de Firebase le permiten ordenar sus datos por cualquier clave secundaria sobre la marcha. Sin embargo, si sabe de antemano cuáles serán sus índices, puede definirlos a través de la regla .indexOn en sus Reglas de seguridad para un mejor rendimiento. Consulte la regla https://firebase.google.com/docs/database/security/indexing-data para obtener más información. Puede leer más sobre orderByChild() en Ordenar datos .
función (consulta...)
obtener (consulta) Obtiene el resultado más actualizado para esta consulta.
off (consulta, tipo de evento, devolución de llamada) Separa una devolución de llamada adjunta previamente con el oyente on () ( onValue , onChildAdded ) correspondiente. Nota: Esta no es la forma recomendada de eliminar un oyente. En su lugar, utilice la función de devolución de llamada devuelta de las respectivas devoluciones on llamada. Separe una devolución de llamada previamente adjunta con on*() . Llamar a off() en un oyente principal no eliminará automáticamente a los oyentes registrados en los nodos secundarios, también se debe llamar a off() en cualquier oyente secundario para eliminar la devolución de llamada. Si no se especifica una devolución de llamada, se eliminarán todas las devoluciones de llamada para el tipo de evento especificado. De manera similar, si no se especifica eventType, se eliminarán todas las devoluciones de llamada para la Reference . Los oyentes individuales también se pueden eliminar invocando sus devoluciones de llamada para darse de baja.
onChildAdded (consulta, devolución de llamada, cancelación de devolución de llamada) Escucha los cambios de datos en una ubicación particular. Esta es la forma principal de leer datos de una base de datos. Su devolución de llamada se activará para los datos iniciales y nuevamente cada vez que cambien los datos. Invoque la devolución de llamada de cancelación de suscripción devuelta para dejar de recibir actualizaciones. Consulte Recuperar datos en la Web para obtener más detalles. Se activará un evento onChildAdded una vez para cada niño inicial en esta ubicación, y se activará nuevamente cada vez que se agregue un nuevo niño. La DataSnapshot que se pasa a la devolución de llamada reflejará los datos del niño correspondiente. Para fines de ordenación, se pasa un segundo argumento que es una cadena que contiene la clave del hijo hermano anterior por orden de clasificación, o null si es el primer hijo.
onChildAdded (consulta, devolución de llamada, opciones) Escucha los cambios de datos en una ubicación particular. Esta es la forma principal de leer datos de una base de datos. Su devolución de llamada se activará para los datos iniciales y nuevamente cada vez que cambien los datos. Invoque la devolución de llamada de cancelación de suscripción devuelta para dejar de recibir actualizaciones. Consulte Recuperar datos en la Web para obtener más detalles. Se activará un evento onChildAdded una vez para cada niño inicial en esta ubicación, y se activará nuevamente cada vez que se agregue un nuevo niño. La DataSnapshot que se pasa a la devolución de llamada reflejará los datos del niño correspondiente. Para fines de ordenación, se pasa un segundo argumento que es una cadena que contiene la clave del hijo hermano anterior por orden de clasificación, o null si es el primer hijo.
onChildAdded (consulta, devolución de llamada, cancelación de devolución de llamada, opciones) Escucha los cambios de datos en una ubicación particular. Esta es la forma principal de leer datos de una base de datos. Su devolución de llamada se activará para los datos iniciales y nuevamente cada vez que cambien los datos. Invoque la devolución de llamada de cancelación de suscripción devuelta para dejar de recibir actualizaciones. Consulte Recuperar datos en la Web para obtener más detalles. Se activará un evento onChildAdded una vez para cada niño inicial en esta ubicación, y se activará nuevamente cada vez que se agregue un nuevo niño. La DataSnapshot que se pasa a la devolución de llamada reflejará los datos del niño correspondiente. Para fines de ordenación, se pasa un segundo argumento que es una cadena que contiene la clave del hijo hermano anterior por orden de clasificación, o null si es el primer hijo.
onChildChanged (consulta, devolución de llamada, cancelar devolución de llamada) Escucha los cambios de datos en una ubicación particular. Esta es la forma principal de leer datos de una base de datos. Su devolución de llamada se activará para los datos iniciales y nuevamente cada vez que cambien los datos. Invoque la devolución de llamada de cancelación de suscripción devuelta para dejar de recibir actualizaciones. Consulte Recuperar datos en la Web para obtener más detalles. Se activará un evento onChildChanged cuando cambien los datos almacenados en un elemento secundario (o cualquiera de sus descendientes). Tenga en cuenta que un solo evento child_changed puede representar varios cambios en el elemento secundario. El DataSnapshot pasado a la devolución de llamada contendrá los nuevos contenidos secundarios. Para fines de ordenación, a la devolución de llamada también se le pasa un segundo argumento que es una cadena que contiene la clave del hijo hermano anterior por orden de clasificación, o null si es el primer hijo.
onChildChanged (consulta, devolución de llamada, opciones) Escucha los cambios de datos en una ubicación particular. Esta es la forma principal de leer datos de una base de datos. Su devolución de llamada se activará para los datos iniciales y nuevamente cada vez que cambien los datos. Invoque la devolución de llamada de cancelación de suscripción devuelta para dejar de recibir actualizaciones. Consulte Recuperar datos en la Web para obtener más detalles. Se activará un evento onChildChanged cuando cambien los datos almacenados en un elemento secundario (o cualquiera de sus descendientes). Tenga en cuenta que un solo evento child_changed puede representar varios cambios en el elemento secundario. El DataSnapshot pasado a la devolución de llamada contendrá los nuevos contenidos secundarios. Para fines de ordenación, a la devolución de llamada también se le pasa un segundo argumento que es una cadena que contiene la clave del hijo hermano anterior por orden de clasificación, o null si es el primer hijo.
onChildChanged (consulta, devolución de llamada, cancelación de devolución de llamada, opciones) Escucha los cambios de datos en una ubicación particular. Esta es la forma principal de leer datos de una base de datos. Su devolución de llamada se activará para los datos iniciales y nuevamente cada vez que cambien los datos. Invoque la devolución de llamada de cancelación de suscripción devuelta para dejar de recibir actualizaciones. Consulte Recuperar datos en la Web para obtener más detalles. Se activará un evento onChildChanged cuando cambien los datos almacenados en un elemento secundario (o cualquiera de sus descendientes). Tenga en cuenta que un solo evento child_changed puede representar varios cambios en el elemento secundario. El DataSnapshot pasado a la devolución de llamada contendrá los nuevos contenidos secundarios. Para fines de ordenación, a la devolución de llamada también se le pasa un segundo argumento que es una cadena que contiene la clave del hijo hermano anterior por orden de clasificación, o null si es el primer hijo.
onChildMoved (consulta, devolución de llamada, cancelar devolución de llamada) Escucha los cambios de datos en una ubicación particular. Esta es la forma principal de leer datos de una base de datos. Su devolución de llamada se activará para los datos iniciales y nuevamente cada vez que cambien los datos. Invoque la devolución de llamada de cancelación de suscripción devuelta para dejar de recibir actualizaciones. Consulte Recuperar datos en la Web para obtener más detalles. Se activará un evento onChildMoved cuando cambie el orden de clasificación de un elemento secundario, de modo que cambie su posición en relación con sus hermanos. El DataSnapshot pasado a la devolución de llamada será para los datos del niño que se ha movido. También se le pasa un segundo argumento que es una cadena que contiene la clave del hijo hermano anterior por orden de clasificación, o null si es el primer hijo.
onChildMoved (consulta, devolución de llamada, opciones) Escucha los cambios de datos en una ubicación particular. Esta es la forma principal de leer datos de una base de datos. Su devolución de llamada se activará para los datos iniciales y nuevamente cada vez que cambien los datos. Invoque la devolución de llamada de cancelación de suscripción devuelta para dejar de recibir actualizaciones. Consulte Recuperar datos en la Web para obtener más detalles. Se activará un evento onChildMoved cuando cambie el orden de clasificación de un elemento secundario, de modo que cambie su posición en relación con sus hermanos. El DataSnapshot pasado a la devolución de llamada será para los datos del niño que se ha movido. También se le pasa un segundo argumento que es una cadena que contiene la clave del hijo hermano anterior por orden de clasificación, o null si es el primer hijo.
onChildMoved (consulta, devolución de llamada, cancelación de devolución de llamada, opciones) Escucha los cambios de datos en una ubicación particular. Esta es la forma principal de leer datos de una base de datos. Su devolución de llamada se activará para los datos iniciales y nuevamente cada vez que cambien los datos. Invoque la devolución de llamada de cancelación de suscripción devuelta para dejar de recibir actualizaciones. Consulte Recuperar datos en la Web para obtener más detalles. Se activará un evento onChildMoved cuando cambie el orden de clasificación de un elemento secundario, de modo que cambie su posición en relación con sus hermanos. El DataSnapshot pasado a la devolución de llamada será para los datos del niño que se ha movido. También se le pasa un segundo argumento que es una cadena que contiene la clave del hijo hermano anterior por orden de clasificación, o null si es el primer hijo.
onChildRemoved (consulta, devolución de llamada, cancelar devolución de llamada) Escucha los cambios de datos en una ubicación particular. Esta es la forma principal de leer datos de una base de datos. Su devolución de llamada se activará para los datos iniciales y nuevamente cada vez que cambien los datos. Invoque la devolución de llamada de cancelación de suscripción devuelta para dejar de recibir actualizaciones. Consulte Recuperar datos en la Web para obtener más detalles. Se activará un evento onChildRemoved una vez cada vez que se elimine un niño. La DataSnapshot pasada a la devolución de llamada serán los datos antiguos del niño que se eliminó. Se eliminará a un niño cuando: - un cliente llama explícitamente remove() en ese hijo o uno de sus ancestros - un cliente llama a set(null) en ese hijo o uno de sus ancestros - ese hijo tiene todos sus hijos eliminados - hay una consulta en efecto que ahora filtra al niño (porque cambió el orden de clasificación o se alcanzó el límite máximo)
onChildRemoved (consulta, devolución de llamada, opciones) Escucha los cambios de datos en una ubicación particular. Esta es la forma principal de leer datos de una base de datos. Su devolución de llamada se activará para los datos iniciales y nuevamente cada vez que cambien los datos. Invoque la devolución de llamada de cancelación de suscripción devuelta para dejar de recibir actualizaciones. Consulte Recuperar datos en la Web para obtener más detalles. Se activará un evento onChildRemoved una vez cada vez que se elimine un niño. La DataSnapshot pasada a la devolución de llamada serán los datos antiguos del niño que se eliminó. Se eliminará a un niño cuando: - un cliente llama explícitamente remove() en ese hijo o uno de sus ancestros - un cliente llama a set(null) en ese hijo o uno de sus ancestros - ese hijo tiene todos sus hijos eliminados - hay una consulta en efecto que ahora filtra al niño (porque cambió el orden de clasificación o se alcanzó el límite máximo)
onChildRemoved (consulta, devolución de llamada, cancelación de devolución de llamada, opciones) Escucha los cambios de datos en una ubicación particular. Esta es la forma principal de leer datos de una base de datos. Su devolución de llamada se activará para los datos iniciales y nuevamente cada vez que cambien los datos. Invoque la devolución de llamada de cancelación de suscripción devuelta para dejar de recibir actualizaciones. Consulte Recuperar datos en la Web para obtener más detalles. Se activará un evento onChildRemoved una vez cada vez que se elimine un niño. La DataSnapshot pasada a la devolución de llamada serán los datos antiguos del niño que se eliminó. Se eliminará a un niño cuando: - un cliente llama explícitamente remove() en ese hijo o uno de sus ancestros - un cliente llama a set(null) en ese hijo o uno de sus ancestros - ese hijo tiene todos sus hijos eliminados - hay una consulta en efecto que ahora filtra al niño (porque cambió el orden de clasificación o se alcanzó el límite máximo)
onValue (consulta, devolución de llamada, cancelar devolución de llamada) Escucha los cambios de datos en una ubicación particular. Esta es la forma principal de leer datos de una base de datos. Su devolución de llamada se activará para los datos iniciales y nuevamente cada vez que cambien los datos. Invoque la devolución de llamada de cancelación de suscripción devuelta para dejar de recibir actualizaciones. Consulte Recuperar datos en la Web para obtener más detalles. Un evento onValue se activará una vez con los datos iniciales almacenados en esta ubicación y luego se activará nuevamente cada vez que cambien los datos. El DataSnapshot pasado a la devolución de llamada será para la ubicación en la que se llamó on() . No se activará hasta que se haya sincronizado todo el contenido. Si la ubicación no tiene datos, se activará con un DataSnapshot vacío ( val() devolverá null ).
onValue (consulta, devolución de llamada, opciones) Escucha los cambios de datos en una ubicación particular. Esta es la forma principal de leer datos de una base de datos. Su devolución de llamada se activará para los datos iniciales y nuevamente cada vez que cambien los datos. Invoque la devolución de llamada de cancelación de suscripción devuelta para dejar de recibir actualizaciones. Consulte Recuperar datos en la Web para obtener más detalles. Un evento onValue se activará una vez con los datos iniciales almacenados en esta ubicación y luego se activará nuevamente cada vez que cambien los datos. El DataSnapshot pasado a la devolución de llamada será para la ubicación en la que se llamó on() . No se activará hasta que se haya sincronizado todo el contenido. Si la ubicación no tiene datos, se activará con un DataSnapshot vacío ( val() devolverá null ).
onValue (consulta, devolución de llamada, cancelación de devolución de llamada, opciones) Escucha los cambios de datos en una ubicación particular. Esta es la forma principal de leer datos de una base de datos. Su devolución de llamada se activará para los datos iniciales y nuevamente cada vez que cambien los datos. Invoque la devolución de llamada de cancelación de suscripción devuelta para dejar de recibir actualizaciones. Consulte Recuperar datos en la Web para obtener más detalles. Un evento onValue se activará una vez con los datos iniciales almacenados en esta ubicación y luego se activará nuevamente cada vez que cambien los datos. El DataSnapshot pasado a la devolución de llamada será para la ubicación en la que se llamó on() . No se activará hasta que se haya sincronizado todo el contenido. Si la ubicación no tiene datos, se activará con un DataSnapshot vacío ( val() devolverá null ).
consulta(consulta, consultaRestricciones) Crea una nueva instancia inmutable de Query que se amplía para incluir también restricciones de consulta adicionales.
función (ref...)
al desconectar (ref) Devuelve un objeto OnDisconnect ; consulte Habilitación de capacidades sin conexión en JavaScript para obtener más información sobre cómo usarlo.
eliminar (ref) Elimina los datos en esta ubicación de la base de datos. También se eliminarán todos los datos de las ubicaciones secundarias. El efecto de la eliminación será visible de inmediato y se activará el evento 'valor' correspondiente. También se iniciará la sincronización de la eliminación con los servidores de Firebase, y la Promesa devuelta se resolverá cuando se complete. Si se proporciona, la devolución de llamada onComplete se llamará de forma asincrónica después de que finalice la sincronización.
ejecutarTransacción(ref, transacciónActualizar, opciones) Modifica atómicamente los datos en esta ubicación. Modifique atómicamente los datos en esta ubicación. A diferencia de un set() normal, que simplemente sobrescribe los datos independientemente de su valor anterior, runTransaction() se usa para modificar el valor existente a un nuevo valor, asegurando que no haya conflictos con otros clientes que escriben en la misma ubicación al mismo tiempo. . Para lograr esto, pasa runTransaction() una función de actualización que se usa para transformar el valor actual en un valor nuevo. Si otro cliente escribe en la ubicación antes de que su nuevo valor se escriba correctamente, su función de actualización se volverá a llamar con el nuevo valor actual y se volverá a intentar la escritura. Esto sucederá repetidamente hasta que su escritura tenga éxito sin conflicto o cancele la transacción al no devolver un valor de su función de actualización. Nota: la modificación de datos con set() cancelará cualquier transacción pendiente en esa ubicación, por lo que se debe tener mucho cuidado si se mezclan set() y runTransaction() para actualizar los mismos datos. Nota: Al usar transacciones con reglas de seguridad y Firebase, tenga en cuenta que un cliente necesita acceso .read además de acceso .write para realizar una transacción. Esto se debe a que la naturaleza de las transacciones del lado del cliente requiere que el cliente lea los datos para actualizarlos transaccionalmente.
conjunto (ref, valor) Escribe datos en esta ubicación de base de datos. Esto sobrescribirá cualquier dato en esta ubicación y todas las ubicaciones secundarias. El efecto de la escritura será visible de inmediato y se activarán los eventos correspondientes ("value", "child_added", etc.). También se iniciará la sincronización de los datos con los servidores de Firebase y la Promesa devuelta se resolverá cuando se complete. Si se proporciona, la devolución de llamada onComplete se llamará de forma asincrónica después de que finalice la sincronización. Pasar null por el nuevo valor es equivalente a llamar remove() ; es decir, se eliminarán todos los datos en esta ubicación y todas las ubicaciones secundarias. set() eliminará cualquier prioridad almacenada en esta ubicación, por lo que si la prioridad debe conservarse, debe usar setWithPriority() en su lugar. Tenga en cuenta que la modificación de datos con set() cancelará cualquier transacción pendiente en esa ubicación, por lo que se debe tener sumo cuidado si se mezclan set() y transaction() para modificar los mismos datos. Un único set() generará un único evento de "valor" en la ubicación donde se realizó el set() .
setPriority(ref, prioridad) Establece una prioridad para los datos en esta ubicación de base de datos. Las aplicaciones no necesitan usar prioridad, pero pueden ordenar colecciones por propiedades ordinarias (consulte Clasificación y filtrado de datos ).
setWithPriority(ref, valor, prioridad) Escribe datos en la ubicación de la base de datos. Como set() pero también especifica la prioridad de esos datos. Las aplicaciones no necesitan usar prioridad, pero pueden ordenar colecciones por propiedades ordinarias (consulte Clasificación y filtrado de datos ).
actualizar (ref, valores) Escribe múltiples valores en la base de datos a la vez. El argumento values contiene varios pares propiedad-valor que se escribirán juntos en la base de datos. Cada propiedad secundaria puede ser una propiedad simple (por ejemplo, "nombre") o una ruta relativa (por ejemplo, "nombre/nombre") desde la ubicación actual hasta los datos que se van a actualizar. A diferencia del método set() , update() se puede usar para actualizar selectivamente solo las propiedades a las que se hace referencia en la ubicación actual (en lugar de reemplazar todas las propiedades secundarias en la ubicación actual). El efecto de la escritura será visible de inmediato y se activarán los eventos correspondientes ('valor', 'niño_agregado', etc.). También se iniciará la sincronización de los datos con los servidores de Firebase y la Promesa devuelta se resolverá cuando se complete. Si se proporciona, la devolución de llamada onComplete se llamará de forma asincrónica después de que finalice la sincronización. Una sola update() generará un solo evento de "valor" en la ubicación donde se realizó la update() , independientemente de cuántos niños se modificaron. Tenga en cuenta que la modificación de datos con update() cancelará cualquier transacción pendiente en esa ubicación, por lo que se debe tener mucho cuidado si se mezclan update() y transaction() para modificar los mismos datos. Pasar null a update() eliminará los datos en esta ubicación. Consulte Introducción de actualizaciones de ubicaciones múltiples y más .
función(valor...)
endAt(valor, clave) Crea una QueryConstraint con el punto final especificado. El uso startAt() , startAfter() , endBefore() , endAt() y equalTo() le permite elegir puntos de inicio y finalización arbitrarios para sus consultas. El punto final es inclusivo, por lo que los elementos secundarios con exactamente el valor especificado se incluirán en la consulta. El argumento clave opcional se puede utilizar para limitar aún más el rango de la consulta. Si se especifica, los elementos secundarios que tienen exactamente el valor especificado también deben tener un nombre de clave menor o igual que la clave especificada. Puede leer más sobre endAt() en Filtrado de datos .
endBefore(valor, clave) Crea una QueryConstraint con el punto final especificado (exclusivo). El uso startAt() , startAfter() , endBefore() , endAt() y equalTo() le permite elegir puntos de inicio y finalización arbitrarios para sus consultas. El punto final es excluyente. Si solo se proporciona un valor, los elementos secundarios con un valor inferior al valor especificado se incluirán en la consulta. Si se especifica una clave, los elementos secundarios deben tener un valor menor o igual que el valor especificado y un nombre de clave menor que la clave especificada.
equalTo(valor, clave) Crea una QueryConstraint que incluye elementos secundarios que coinciden con el valor especificado. El uso startAt() , startAfter() , endBefore() , endAt() y equalTo() le permite elegir puntos de inicio y finalización arbitrarios para sus consultas. El argumento clave opcional se puede utilizar para limitar aún más el rango de la consulta. Si se especifica, los elementos secundarios que tienen exactamente el valor especificado también deben tener exactamente la clave especificada como nombre de clave. Esto se puede usar para filtrar conjuntos de resultados con muchas coincidencias para el mismo valor. Puede leer más sobre equalTo() en Filtrado de datos .
startAfter(valor, clave) Crea una QueryConstraint con el punto de partida especificado (exclusivo). El uso startAt() , startAfter() , endBefore() , endAt() y equalTo() le permite elegir puntos de inicio y finalización arbitrarios para sus consultas. El punto de partida es excluyente. Si solo se proporciona un valor, los elementos secundarios con un valor mayor que el valor especificado se incluirán en la consulta. Si se especifica una clave, los elementos secundarios deben tener un valor mayor o igual que el valor especificado y un nombre de clave mayor que la clave especificada.
startAt(valor, clave) Crea una QueryConstraint con el punto de partida especificado. El uso startAt() , startAfter() , endBefore() , endAt() y equalTo() le permite elegir puntos de inicio y finalización arbitrarios para sus consultas. El punto de partida es inclusivo, por lo que los elementos secundarios con exactamente el valor especificado se incluirán en la consulta. El argumento clave opcional se puede utilizar para limitar aún más el rango de la consulta. Si se especifica, los elementos secundarios que tienen exactamente el valor especificado también deben tener un nombre de clave mayor o igual que la clave especificada. Puede leer más sobre startAt() en Filtrado de datos .

Clases

Clase Descripción
Base de datos Clase que representa una base de datos en tiempo real de Firebase.
Instantánea de datos Una DataSnapshot contiene datos de una ubicación de base de datos. Cada vez que lee datos de la base de datos, los recibe como una DataSnapshot . Se pasa una DataSnapshot a las devoluciones de llamada de eventos que adjuntas con on() o once() . Puede extraer el contenido de la instantánea como un objeto de JavaScript llamando al método val() . Alternativamente, puede atravesar la instantánea llamando child() para devolver instantáneas secundarias (a las que luego podría llamar val() ). Una DataSnapshot es una copia inmutable y generada eficientemente de los datos en una ubicación de la base de datos. No se puede modificar y nunca cambiará (para modificar datos, siempre llama directamente al método set() en una Reference ).
Al Desconectar La clase onDisconnect le permite escribir o borrar datos cuando su cliente se desconecta del servidor de la base de datos. Estas actualizaciones ocurren ya sea que su cliente se desconecte limpiamente o no, por lo que puede confiar en ellas para limpiar los datos incluso si se interrumpe una conexión o si un cliente falla. La clase onDisconnect se usa más comúnmente para administrar la presencia en aplicaciones donde es útil detectar cuántos clientes están conectados y cuándo otros clientes se desconectan. Consulte Habilitación de funciones sin conexión en JavaScript para obtener más información. Para evitar problemas cuando se interrumpe una conexión antes de que las solicitudes se puedan transferir al servidor de la base de datos, estas funciones deben llamarse antes de escribir cualquier dato. Tenga en cuenta que las operaciones onDisconnect solo se activan una vez. Si desea que se produzca una operación cada vez que se produzca una desconexión, deberá restablecer las operaciones onDisconnect cada vez que se vuelva a conectar.
Restricción de consulta Una QueryConstraint se utiliza para limitar el conjunto de documentos devueltos por una consulta de base de datos. Las QueryConstraint se crean invocando endAt() , terminarAntes() , empezar en() , empezarDespués() , limiteAlPrimero() , limiteAlÚltimo() , ordenarPorNiño() , ordenarPorNiño() , orderByKey() , orderByPriority() , orderByValue() o equalTo() y luego se pueden pasar a query() para crear una nueva instancia de consulta que también contenga esta QueryConstraint .
Resultado de la transacción Un tipo para el valor de resolución de runTransaction() .

Interfaces

Interfaz Descripción
Base de datosReferencia Una DatabaseReference representa una ubicación específica en su base de datos y se puede usar para leer o escribir datos en esa ubicación de la base de datos. Puede hacer referencia a la ubicación raíz o secundaria en su base de datos llamando a ref() o ref("child/path") . La escritura se realiza con el método set() y la lectura se puede realizar con el método on*() . Consulte https://firebase.google.com/docs/database/web/read-and-write
Instantánea de datos iterados Representa una instantánea secundaria de una Reference que se está iterando. La clave nunca será indefinida.
ListenOptions Un objeto de opciones que se puede usar para personalizar un oyente.
Consulta Una Query ordena y filtra los datos en una ubicación de la base de datos para que solo se incluya un subconjunto de los datos secundarios. Esto se puede usar para ordenar una colección de datos por algún atributo (por ejemplo, la altura de los dinosaurios), así como para restringir una gran lista de elementos (por ejemplo, mensajes de chat) a un número adecuado para sincronizar con el cliente. Las consultas se crean encadenando uno o más de los métodos de filtro definidos aquí. Al igual que con una DatabaseReference , puede recibir datos de una Query utilizando los métodos on*() . Solo recibirá eventos y DataSnapshot para el subconjunto de datos que coincidan con su consulta. Consulte https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data para obtener más información.
Referencia entoncesable Una Promise que también puede actuar como una DatabaseReference cuando es devuelta por push() . La referencia está disponible de inmediato y Promise se resuelve cuando se completa la escritura en el backend.
Opciones de transacción Un objeto de opciones para configurar transacciones.

Tipo de alias

Alias ​​de tipo Descripción
Tipo de evento Una de las siguientes cadenas: "valor", "child_added", "child_changed", "child_removed" o "child_moved".
QueryConstraintType Describe las diferentes restricciones de consulta disponibles en este SDK.
Darse de baja Una devolución de llamada que se puede invocar para eliminar un oyente.

obtenerbase de datos()

Devuelve la instancia del SDK de Realtime Database que está asociado con la FirebaseApp proporcionada. . Inicializa una nueva instancia con la configuración predeterminada si no existe ninguna instancia o si la instancia existente usa una URL de base de datos personalizada.

Firma:

export declare function getDatabase(app?: FirebaseApp, url?: string): Database;

Parámetros

Parámetro Tipo Descripción
aplicación FirebaseApp La instancia de FirebaseApp con la que está asociada la instancia de Realtime Database devuelta.
URL cadena La URL de la instancia de Realtime Database a la que conectarse. Si no se proporciona, el SDK se conecta a la instancia predeterminada de la aplicación Firebase.

Devoluciones:

Base de datos

La instancia Database de la aplicación proporcionada.

conectarDatabaseEmulator()

Modifique la instancia proporcionada para comunicarse con el emulador de Realtime Database.

Nota: Este método debe llamarse antes de realizar cualquier otra operación.

Firma:

export declare function connectDatabaseEmulator(db: Database, host: string, port: number, options?: {
    mockUserToken?: EmulatorMockTokenOptions | string;
}): void;

Parámetros

Parámetro Tipo Descripción
base de datos Base de datos La instancia a modificar.
anfitrión cadena El host del emulador (por ejemplo: localhost)
puerto número El puerto del emulador (ej: 8080)
opciones { mockUserToken?: EmulatorMockTokenOptions | cadena; }

Devoluciones:

vacío

salir de línea()

Se desconecta del servidor (todas las operaciones de la base de datos se completarán sin conexión).

The client automatically maintains a persistent connection to the Database server, which will remain active indefinitely and reconnect when disconnected. However, the goOffline() and goOnline() methods may be used to control the client connection in cases where a persistent connection is undesirable.

While offline, the client will no longer receive data updates from the Database. However, all Database operations performed locally will continue to immediately fire events, allowing your application to continue behaving normally. Additionally, each operation performed locally will automatically be queued and retried upon reconnection to the Database server.

To reconnect to the Database and begin receiving remote events, see goOnline() .

Firma:

export declare function goOffline(db: Database): void;

Parámetros

Parámetro Tipo Descripción
db Database The instance to disconnect.

Devoluciones:

vacío

goOnline()

Reconnects to the server and synchronizes the offline Database state with the server state.

This method should be used after disabling the active connection with goOffline() . Once reconnected, the client will transmit the proper data and fire the appropriate events so that your client "catches up" automatically.

Firma:

export declare function goOnline(db: Database): void;

Parámetros

Parámetro Tipo Descripción
db Database The instance to reconnect.

Devoluciones:

vacío

ref()

Returns a Reference representing the location in the Database corresponding to the provided path. If no path is provided, the Reference will point to the root of the Database.

Firma:

export declare function ref(db: Database, path?: string): DatabaseReference;

Parámetros

Parámetro Tipo Descripción
db Database The database instance to obtain a reference for.
camino cadena Optional path representing the location the returned Reference will point. If not provided, the returned Reference will point to the root of the Database.

Devoluciones:

Base de datosReferencia

If a path is provided, a Reference pointing to the provided path. Otherwise, a Reference pointing to the root of the Database.

refFromURL()

Returns a Reference representing the location in the Database corresponding to the provided Firebase URL.

An exception is thrown if the URL is not a valid Firebase Database URL or it has a different domain than the current Database instance.

Note that all query parameters ( orderBy , limitToLast , etc.) are ignored and are not applied to the returned Reference .

Firma:

export declare function refFromURL(db: Database, url: string): DatabaseReference;

Parámetros

Parámetro Tipo Descripción
db Database The database instance to obtain a reference for.
url cadena The Firebase URL at which the returned Reference will point.

Devoluciones:

Base de datosReferencia

A Reference pointing to the provided Firebase URL.

forceLongPolling()

Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.

Firma:

export declare function forceLongPolling(): void;

Devoluciones:

vacío

forceWebSockets()

Force the use of websockets instead of longPolling.

Firma:

export declare function forceWebSockets(): void;

Devoluciones:

vacío

orderByKey()

Creates a new QueryConstraint that orders by the key.

Sorts the results of a query by their (ascending) key values.

You can read more about orderByKey() in Sort data .

Firma:

export declare function orderByKey(): QueryConstraint;

Devoluciones:

Restricción de consulta

orderByPriority()

Creates a new QueryConstraint that orders by priority.

Applications need not use priority but can order collections by ordinary properties (see Sort data for alternatives to priority.

Firma:

export declare function orderByPriority(): QueryConstraint;

Devoluciones:

Restricción de consulta

orderByValue()

Creates a new QueryConstraint that orders by value.

If the children of a query are all scalar values (string, number, or boolean), you can order the results by their (ascending) values.

You can read more about orderByValue() in Sort data .

Firma:

export declare function orderByValue(): QueryConstraint;

Devoluciones:

Restricción de consulta

serverTimestamp()

Returns a placeholder value for auto-populating the current timestamp (time since the Unix epoch, in milliseconds) as determined by the Firebase servers.

Firma:

export declare function serverTimestamp(): object;

Devoluciones:

object

increment()

Returns a placeholder value that can be used to atomically increment the current database value by the provided delta.

Firma:

export declare function increment(delta: number): object;

Parámetros

Parámetro Tipo Descripción
delta número the amount to modify the current value atomically.

Devoluciones:

object

A placeholder value for modifying data atomically server-side.

enableLogging()

Logs debugging information to the console.

Firma:

export declare function enableLogging(enabled: boolean, persistent?: boolean): any;

Parámetros

Parámetro Tipo Descripción
enabled booleano Enables logging if true , disables logging if false .
persistent booleano Remembers the logging state between page refreshes if true .

Devoluciones:

cualquier

limitToFirst()

Creates a new QueryConstraint that if limited to the first specific number of children.

The limitToFirst() method is used to set a maximum number of children to be synced for a given callback. If we set a limit of 100, we will initially only receive up to 100 child_added events. If we have fewer than 100 messages stored in our Database, a child_added event will fire for each message. However, if we have over 100 messages, we will only receive a child_added event for the first 100 ordered messages. As items change, we will receive child_removed events for each item that drops out of the active list so that the total number stays at 100.

You can read more about limitToFirst() in Filtering data .

Firma:

export declare function limitToFirst(limit: number): QueryConstraint;

Parámetros

Parámetro Tipo Descripción
limit número The maximum number of nodes to include in this query.

Devoluciones:

Restricción de consulta

limitToLast()

Creates a new QueryConstraint that is limited to return only the last specified number of children.

The limitToLast() method is used to set a maximum number of children to be synced for a given callback. If we set a limit of 100, we will initially only receive up to 100 child_added events. If we have fewer than 100 messages stored in our Database, a child_added event will fire for each message. However, if we have over 100 messages, we will only receive a child_added event for the last 100 ordered messages. As items change, we will receive child_removed events for each item that drops out of the active list so that the total number stays at 100.

You can read more about limitToLast() in Filtering data .

Firma:

export declare function limitToLast(limit: number): QueryConstraint;

Parámetros

Parámetro Tipo Descripción
limit número The maximum number of nodes to include in this query.

Devoluciones:

Restricción de consulta

enableLogging()

Logs debugging information to the console.

Firma:

export declare function enableLogging(logger: (message: string) => unknown): any;

Parámetros

Parámetro Tipo Descripción
logger (message: string) => unknown A custom logger function to control how things get logged.

Devoluciones:

cualquier

child()

Gets a Reference for the location at the specified relative path.

The relative path can either be a simple child name (for example, "ada") or a deeper slash-separated path (for example, "ada/name/first").

Firma:

export declare function child(parent: DatabaseReference, path: string): DatabaseReference;

Parámetros

Parámetro Tipo Descripción
parent Base de datosReferencia The parent location.
camino cadena A relative path from this location to the desired child location.

Devoluciones:

Base de datosReferencia

The specified child location.

push()

Generates a new child location using a unique key and returns its Reference .

This is the most common pattern for adding data to a collection of items.

If you provide a value to push() , the value is written to the generated location. If you don't pass a value, nothing is written to the database and the child remains empty (but you can use the Reference elsewhere).

The unique keys generated by push() are ordered by the current time, so the resulting list of items is chronologically sorted. The keys are also designed to be unguessable (they contain 72 random bits of entropy).

See Append to a list of data . See The 2^120 Ways to Ensure Unique Identifiers .

Firma:

export declare function push(parent: DatabaseReference, value?: unknown): ThenableReference;

Parámetros

Parámetro Tipo Descripción
parent Base de datosReferencia The parent location.
value unknown Optional value to be written at the generated location.

Devoluciones:

ThenableReference

Combined Promise and Reference ; resolves when write is complete, but can be used immediately as the Reference to the child location.

orderByChild()

Creates a new QueryConstraint that orders by the specified child key.

Queries can only order by one key at a time. Calling orderByChild() multiple times on the same query is an error.

Firebase queries allow you to order your data by any child key on the fly. However, if you know in advance what your indexes will be, you can define them via the .indexOn rule in your Security Rules for better performance. See the https://firebase.google.com/docs/database/security/indexing-data rule for more information.

You can read more about orderByChild() in Sort data .

Firma:

export declare function orderByChild(path: string): QueryConstraint;

Parámetros

Parámetro Tipo Descripción
camino cadena The path to order by.

Devoluciones:

Restricción de consulta

get()

Gets the most up-to-date result for this query.

Firma:

export declare function get(query: Query): Promise<DataSnapshot>;

Parámetros

Parámetro Tipo Descripción
query Consulta The query to run.

Devoluciones:

Promise< DataSnapshot >

A Promise which resolves to the resulting DataSnapshot if a value is available, or rejects if the client is unable to return a value (eg, if the server is unreachable and there is nothing cached).

off()

Detaches a callback previously attached with the corresponding on*() ( onValue , onChildAdded ) listener. Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from the respective on* callbacks.

Detach a callback previously attached with on*() . Calling off() on a parent listener will not automatically remove listeners registered on child nodes, off() must also be called on any child listeners to remove the callback.

If a callback is not specified, all callbacks for the specified eventType will be removed. Similarly, if no eventType is specified, all callbacks for the Reference will be removed.

Individual listeners can also be removed by invoking their unsubscribe callbacks.

Firma:

export declare function off(query: Query, eventType?: EventType, callback?: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown): void;

Parámetros

Parámetro Tipo Descripción
query Consulta The query that the listener was registered with.
eventType EventType One of the following strings: "value", "child_added", "child_changed", "child_removed", or "child_moved." If omitted, all callbacks for the Reference will be removed.
callback (snapshot: DataSnapshot , previousChildName?: string | null) => unknown The callback function that was passed to on() or undefined to remove all callbacks.

Devoluciones:

vacío

onChildAdded()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildAdded event will be triggered once for each initial child at this location, and it will be triggered again every time a new child is added. The DataSnapshot passed into the callback will reflect the data for the relevant child. For ordering purposes, it is passed a second argument which is a string containing the key of the previous sibling child by sort order, or null if it is the first child.

Firma:

export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe;

Parámetros

Parámetro Tipo Descripción
query Consulta The query to run.
callback (snapshot: DataSnapshot , previousChildName?: string | null) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.

Devoluciones:

Unsubscribe

A function that can be invoked to remove the listener.

onChildAdded()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildAdded event will be triggered once for each initial child at this location, and it will be triggered again every time a new child is added. The DataSnapshot passed into the callback will reflect the data for the relevant child. For ordering purposes, it is passed a second argument which is a string containing the key of the previous sibling child by sort order, or null if it is the first child.

Firma:

export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe;

Parámetros

Parámetro Tipo Descripción
query Consulta The query to run.
callback (snapshot: DataSnapshot , previousChildName: string | null) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
opciones ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Devoluciones:

Unsubscribe

A function that can be invoked to remove the listener.

onChildAdded()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildAdded event will be triggered once for each initial child at this location, and it will be triggered again every time a new child is added. The DataSnapshot passed into the callback will reflect the data for the relevant child. For ordering purposes, it is passed a second argument which is a string containing the key of the previous sibling child by sort order, or null if it is the first child.

Firma:

export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe;

Parámetros

Parámetro Tipo Descripción
query Consulta The query to run.
callback (snapshot: DataSnapshot , previousChildName: string | null) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.
opciones ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Devoluciones:

Unsubscribe

A function that can be invoked to remove the listener.

onChildChanged()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildChanged event will be triggered when the data stored in a child (or any of its descendants) changes. Note that a single child_changed event may represent multiple changes to the child. The DataSnapshot passed to the callback will contain the new child contents. For ordering purposes, the callback is also passed a second argument which is a string containing the key of the previous sibling child by sort order, or null if it is the first child.

Firma:

export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe;

Parámetros

Parámetro Tipo Descripción
query Consulta The query to run.
callback (snapshot: DataSnapshot , previousChildName: string | null) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.

Devoluciones:

Unsubscribe

A function that can be invoked to remove the listener.

onChildChanged()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildChanged event will be triggered when the data stored in a child (or any of its descendants) changes. Note that a single child_changed event may represent multiple changes to the child. The DataSnapshot passed to the callback will contain the new child contents. For ordering purposes, the callback is also passed a second argument which is a string containing the key of the previous sibling child by sort order, or null if it is the first child.

Firma:

export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe;

Parámetros

Parámetro Tipo Descripción
query Consulta The query to run.
callback (snapshot: DataSnapshot , previousChildName: string | null) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
opciones ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Devoluciones:

Unsubscribe

A function that can be invoked to remove the listener.

onChildChanged()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildChanged event will be triggered when the data stored in a child (or any of its descendants) changes. Note that a single child_changed event may represent multiple changes to the child. The DataSnapshot passed to the callback will contain the new child contents. For ordering purposes, the callback is also passed a second argument which is a string containing the key of the previous sibling child by sort order, or null if it is the first child.

Firma:

export declare function onChildChanged(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe;

Parámetros

Parámetro Tipo Descripción
query Consulta The query to run.
callback (snapshot: DataSnapshot , previousChildName: string | null) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.
opciones ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Devoluciones:

Unsubscribe

A function that can be invoked to remove the listener.

onChildMoved()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildMoved event will be triggered when a child's sort order changes such that its position relative to its siblings changes. The DataSnapshot passed to the callback will be for the data of the child that has moved. It is also passed a second argument which is a string containing the key of the previous sibling child by sort order, or null if it is the first child.

Firma:

export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe;

Parámetros

Parámetro Tipo Descripción
query Consulta The query to run.
callback (snapshot: DataSnapshot , previousChildName: string | null) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.

Devoluciones:

Unsubscribe

A function that can be invoked to remove the listener.

onChildMoved()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildMoved event will be triggered when a child's sort order changes such that its position relative to its siblings changes. The DataSnapshot passed to the callback will be for the data of the child that has moved. It is also passed a second argument which is a string containing the key of the previous sibling child by sort order, or null if it is the first child.

Firma:

export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe;

Parámetros

Parámetro Tipo Descripción
query Consulta The query to run.
callback (snapshot: DataSnapshot , previousChildName: string | null) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
opciones ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Devoluciones:

Unsubscribe

A function that can be invoked to remove the listener.

onChildMoved()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildMoved event will be triggered when a child's sort order changes such that its position relative to its siblings changes. The DataSnapshot passed to the callback will be for the data of the child that has moved. It is also passed a second argument which is a string containing the key of the previous sibling child by sort order, or null if it is the first child.

Firma:

export declare function onChildMoved(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe;

Parámetros

Parámetro Tipo Descripción
query Consulta The query to run.
callback (snapshot: DataSnapshot , previousChildName: string | null) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.
opciones ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Devoluciones:

Unsubscribe

A function that can be invoked to remove the listener.

onChildRemoved()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildRemoved event will be triggered once every time a child is removed. The DataSnapshot passed into the callback will be the old data for the child that was removed. A child will get removed when either:

  • a client explicitly calls remove() on that child or one of its ancestors - a client calls set(null) on that child or one of its ancestors - that child has all of its children removed - there is a query in effect which now filters out the child (because it's sort order changed or the max limit was hit)

Firma:

export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe;

Parámetros

Parámetro Tipo Descripción
query Consulta The query to run.
callback (snapshot: DataSnapshot ) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.

Devoluciones:

Unsubscribe

A function that can be invoked to remove the listener.

onChildRemoved()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildRemoved event will be triggered once every time a child is removed. The DataSnapshot passed into the callback will be the old data for the child that was removed. A child will get removed when either:

  • a client explicitly calls remove() on that child or one of its ancestors - a client calls set(null) on that child or one of its ancestors - that child has all of its children removed - there is a query in effect which now filters out the child (because it's sort order changed or the max limit was hit)

Firma:

export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, options: ListenOptions): Unsubscribe;

Parámetros

Parámetro Tipo Descripción
query Consulta The query to run.
callback (snapshot: DataSnapshot ) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
opciones ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Devoluciones:

Unsubscribe

A function that can be invoked to remove the listener.

onChildRemoved()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onChildRemoved event will be triggered once every time a child is removed. The DataSnapshot passed into the callback will be the old data for the child that was removed. A child will get removed when either:

  • a client explicitly calls remove() on that child or one of its ancestors - a client calls set(null) on that child or one of its ancestors - that child has all of its children removed - there is a query in effect which now filters out the child (because it's sort order changed or the max limit was hit)

Firma:

export declare function onChildRemoved(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe;

Parámetros

Parámetro Tipo Descripción
query Consulta The query to run.
callback (snapshot: DataSnapshot ) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot and a string containing the key of the previous child, by sort order, or null if it is the first child.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.
opciones ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Devoluciones:

Unsubscribe

A function that can be invoked to remove the listener.

onValue()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onValue event will trigger once with the initial data stored at this location, and then trigger again each time the data changes. The DataSnapshot passed to the callback will be for the location at which on() was called. It won't trigger until the entire contents has been synchronized. If the location has no data, it will be triggered with an empty DataSnapshot ( val() will return null ).

Firma:

export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe;

Parámetros

Parámetro Tipo Descripción
query Consulta The query to run.
callback (snapshot: DataSnapshot ) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.

Devoluciones:

Unsubscribe

A function that can be invoked to remove the listener.

onValue()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onValue event will trigger once with the initial data stored at this location, and then trigger again each time the data changes. The DataSnapshot passed to the callback will be for the location at which on() was called. It won't trigger until the entire contents has been synchronized. If the location has no data, it will be triggered with an empty DataSnapshot ( val() will return null ).

Firma:

export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, options: ListenOptions): Unsubscribe;

Parámetros

Parámetro Tipo Descripción
query Consulta The query to run.
callback (snapshot: DataSnapshot ) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot.
opciones ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Devoluciones:

Unsubscribe

A function that can be invoked to remove the listener.

onValue()

Listens for data changes at a particular location.

This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details.

An onValue event will trigger once with the initial data stored at this location, and then trigger again each time the data changes. The DataSnapshot passed to the callback will be for the location at which on() was called. It won't trigger until the entire contents has been synchronized. If the location has no data, it will be triggered with an empty DataSnapshot ( val() will return null ).

Firma:

export declare function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback: (error: Error) => unknown, options: ListenOptions): Unsubscribe;

Parámetros

Parámetro Tipo Descripción
query Consulta The query to run.
callback (snapshot: DataSnapshot ) => unknown A callback that fires when the specified event occurs. The callback will be passed a DataSnapshot.
cancelCallback (error: Error) => unknown An optional callback that will be notified if your event subscription is ever canceled because your client does not have permission to read this data (or it had permission but has now lost it). This callback will be passed an Error object indicating why the failure occurred.
opciones ListenOptions An object that can be used to configure onlyOnce , which then removes the listener after its first invocation.

Devoluciones:

Unsubscribe

A function that can be invoked to remove the listener.

query()

Crea una nueva instancia inmutable de Query que se amplía para incluir también restricciones de consulta adicionales.

Firma:

export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query;

Parámetros

Parámetro Tipo Descripción
query Consulta The Query instance to use as a base for the new constraints.
queryConstraints Restricción de consulta [] The list of QueryConstraint s to apply.

Devoluciones:

Consulta

Exceptions

if any of the provided query constraints cannot be combined with the existing or new constraints.

onDisconnect()

Returns an OnDisconnect object - see Enabling Offline Capabilities in JavaScript for more information on how to use it.

Firma:

export declare function onDisconnect(ref: DatabaseReference): OnDisconnect;

Parámetros

Parámetro Tipo Descripción
ref Base de datosReferencia The reference to add OnDisconnect triggers for.

Devoluciones:

OnDisconnect

remove()

Removes the data at this Database location.

Any data at child locations will also be deleted.

The effect of the remove will be visible immediately and the corresponding event 'value' will be triggered. Synchronization of the remove to the Firebase servers will also be started, and the returned Promise will resolve when complete. If provided, the onComplete callback will be called asynchronously after synchronization has finished.

Firma:

export declare function remove(ref: DatabaseReference): Promise<void>;

Parámetros

Parámetro Tipo Descripción
ref Base de datosReferencia The location to remove.

Devoluciones:

Promise<void>

Resolves when remove on server is complete.

runTransaction()

Atomically modifies the data at this location.

Atomically modify the data at this location. Unlike a normal set() , which just overwrites the data regardless of its previous value, runTransaction() is used to modify the existing value to a new value, ensuring there are no conflicts with other clients writing to the same location at the same time.

To accomplish this, you pass runTransaction() an update function which is used to transform the current value into a new value. If another client writes to the location before your new value is successfully written, your update function will be called again with the new current value, and the write will be retried. This will happen repeatedly until your write succeeds without conflict or you abort the transaction by not returning a value from your update function.

Firma:

export declare function runTransaction(ref: DatabaseReference, transactionUpdate: (currentData: any) => unknown, options?: TransactionOptions): Promise<TransactionResult>;

Parámetros

Parámetro Tipo Descripción
ref Base de datosReferencia The location to atomically modify.
transactionUpdate (currentData: any) => unknown A developer-supplied function which will be passed the current data stored at this location (as a JavaScript object). The function should return the new value it would like written (as a JavaScript object). If undefined is returned (ie you return with no arguments) the transaction will be aborted and the data at this location will not be modified.
opciones TransactionOptions An options object to configure transactions.

Devoluciones:

Promise< TransactionResult >

A Promise that can optionally be used instead of the onComplete callback to handle success and failure.

set()

Writes data to this Database location.

This will overwrite any data at this location and all child locations.

The effect of the write will be visible immediately, and the corresponding events ("value", "child_added", etc.) will be triggered. Synchronization of the data to the Firebase servers will also be started, and the returned Promise will resolve when complete. If provided, the onComplete callback will be called asynchronously after synchronization has finished.

Passing null for the new value is equivalent to calling remove() ; namely, all data at this location and all child locations will be deleted.

set() will remove any priority stored at this location, so if priority is meant to be preserved, you need to use setWithPriority() instead.

Note that modifying data with set() will cancel any pending transactions at that location, so extreme care should be taken if mixing set() and transaction() to modify the same data.

A single set() will generate a single "value" event at the location where the set() was performed.

Firma:

export declare function set(ref: DatabaseReference, value: unknown): Promise<void>;

Parámetros

Parámetro Tipo Descripción
ref Base de datosReferencia The location to write to.
value unknown The value to be written (string, number, boolean, object, array, or null).

Devoluciones:

Promise<void>

Resolves when write to server is complete.

setPriority()

Sets a priority for the data at this Database location.

Las aplicaciones no necesitan usar prioridad, pero pueden ordenar colecciones por propiedades ordinarias (consulte Clasificación y filtrado de datos ).

Firma:

export declare function setPriority(ref: DatabaseReference, priority: string | number | null): Promise<void>;

Parámetros

Parámetro Tipo Descripción
ref Base de datosReferencia The location to write to.
priority cadena | número | nulo The priority to be written (string, number, or null).

Devoluciones:

Promise<void>

Resolves when write to server is complete.

setWithPriority()

Writes data the Database location. Like set() but also specifies the priority for that data.

Las aplicaciones no necesitan usar prioridad, pero pueden ordenar colecciones por propiedades ordinarias (consulte Clasificación y filtrado de datos ).

Firma:

export declare function setWithPriority(ref: DatabaseReference, value: unknown, priority: string | number | null): Promise<void>;

Parámetros

Parámetro Tipo Descripción
ref Base de datosReferencia The location to write to.
value unknown The value to be written (string, number, boolean, object, array, or null).
priority cadena | número | nulo The priority to be written (string, number, or null).

Devoluciones:

Promise<void>

Resolves when write to server is complete.

update()

Writes multiple values to the Database at once.

The values argument contains multiple property-value pairs that will be written to the Database together. Each child property can either be a simple property (for example, "name") or a relative path (for example, "name/first") from the current location to the data to update.

As opposed to the set() method, update() can be use to selectively update only the referenced properties at the current location (instead of replacing all the child properties at the current location).

The effect of the write will be visible immediately, and the corresponding events ('value', 'child_added', etc.) will be triggered. Synchronization of the data to the Firebase servers will also be started, and the returned Promise will resolve when complete. If provided, the onComplete callback will be called asynchronously after synchronization has finished.

A single update() will generate a single "value" event at the location where the update() was performed, regardless of how many children were modified.

Note that modifying data with update() will cancel any pending transactions at that location, so extreme care should be taken if mixing update() and transaction() to modify the same data.

Passing null to update() will remove the data at this location.

See Introducing multi-location updates and more .

Firma:

export declare function update(ref: DatabaseReference, values: object): Promise<void>;

Parámetros

Parámetro Tipo Descripción
ref Base de datosReferencia The location to write to.
values object Object containing multiple values.

Devoluciones:

Promise<void>

Resolves when update on server is complete.

endAt()

Creates a QueryConstraint with the specified ending point.

Using startAt() , startAfter() , endBefore() , endAt() and equalTo() allows you to choose arbitrary starting and ending points for your queries.

The ending point is inclusive, so children with exactly the specified value will be included in the query. The optional key argument can be used to further limit the range of the query. If it is specified, then children that have exactly the specified value must also have a key name less than or equal to the specified key.

You can read more about endAt() in Filtering data .

Firma:

export declare function endAt(value: number | string | boolean | null, key?: string): QueryConstraint;

Parámetros

Parámetro Tipo Descripción
value número | cadena | boolean | nulo The value to end at. The argument type depends on which orderBy () function was used in this query. Specify a value that matches the orderBy () type. When used in combination with orderByKey() , the value must be a string.
key cadena The child key to end at, among the children with the previously specified priority. This argument is only allowed if ordering by child, value, or priority.

Devoluciones:

Restricción de consulta

endBefore()

Creates a QueryConstraint with the specified ending point (exclusive).

Using startAt() , startAfter() , endBefore() , endAt() and equalTo() allows you to choose arbitrary starting and ending points for your queries.

The ending point is exclusive. If only a value is provided, children with a value less than the specified value will be included in the query. If a key is specified, then children must have a value less than or equal to the specified value and a key name less than the specified key.

Firma:

export declare function endBefore(value: number | string | boolean | null, key?: string): QueryConstraint;

Parámetros

Parámetro Tipo Descripción
value número | cadena | boolean | nulo The value to end before. The argument type depends on which orderBy () function was used in this query. Specify a value that matches the orderBy () type. When used in combination with orderByKey() , the value must be a string.
key cadena The child key to end before, among the children with the previously specified priority. This argument is only allowed if ordering by child, value, or priority.

Devoluciones:

Restricción de consulta

equalTo()

Creates a QueryConstraint that includes children that match the specified value.

Using startAt() , startAfter() , endBefore() , endAt() and equalTo() allows you to choose arbitrary starting and ending points for your queries.

The optional key argument can be used to further limit the range of the query. If it is specified, then children that have exactly the specified value must also have exactly the specified key as their key name. This can be used to filter result sets with many matches for the same value.

You can read more about equalTo() in Filtering data .

Firma:

export declare function equalTo(value: number | string | boolean | null, key?: string): QueryConstraint;

Parámetros

Parámetro Tipo Descripción
value número | cadena | boolean | nulo The value to match for. The argument type depends on which orderBy () function was used in this query. Specify a value that matches the orderBy () type. When used in combination with orderByKey() , the value must be a string.
key cadena The child key to start at, among the children with the previously specified priority. This argument is only allowed if ordering by child, value, or priority.

Devoluciones:

Restricción de consulta

startAfter()

Creates a QueryConstraint with the specified starting point (exclusive).

Using startAt() , startAfter() , endBefore() , endAt() and equalTo() allows you to choose arbitrary starting and ending points for your queries.

The starting point is exclusive. If only a value is provided, children with a value greater than the specified value will be included in the query. If a key is specified, then children must have a value greater than or equal to the specified value and aa key name greater than the specified key.

Firma:

export declare function startAfter(value: number | string | boolean | null, key?: string): QueryConstraint;

Parámetros

Parámetro Tipo Descripción
value número | cadena | boolean | nulo The value to start after. The argument type depends on which orderBy () function was used in this query. Specify a value that matches the orderBy () type. When used in combination with orderByKey() , the value must be a string.
key cadena The child key to start after. This argument is only allowed if ordering by child, value, or priority.

Devoluciones:

Restricción de consulta

startAt()

Creates a QueryConstraint with the specified starting point.

Using startAt() , startAfter() , endBefore() , endAt() and equalTo() allows you to choose arbitrary starting and ending points for your queries.

The starting point is inclusive, so children with exactly the specified value will be included in the query. The optional key argument can be used to further limit the range of the query. If it is specified, then children that have exactly the specified value must also have a key name greater than or equal to the specified key.

You can read more about startAt() in Filtering data .

Firma:

export declare function startAt(value?: number | string | boolean | null, key?: string): QueryConstraint;

Parámetros

Parámetro Tipo Descripción
value número | cadena | boolean | nulo The value to start at. The argument type depends on which orderBy () function was used in this query. Specify a value that matches the orderBy () type. When used in combination with orderByKey() , the value must be a string.
key cadena The child key to start at. This argument is only allowed if ordering by child, value, or priority.

Devoluciones:

Restricción de consulta

EventType

One of the following strings: "value", "child_added", "child_changed", "child_removed", or "child_moved."

Firma:

export declare type EventType = 'value' | 'child_added' | 'child_changed' | 'child_moved' | 'child_removed';

QueryConstraintType

Describes the different query constraints available in this SDK.

Firma:

export declare type QueryConstraintType = 'endAt' | 'endBefore' | 'startAt' | 'startAfter' | 'limitToFirst' | 'limitToLast' | 'orderByChild' | 'orderByKey' | 'orderByPriority' | 'orderByValue' | 'equalTo';

Unsubscribe

A callback that can invoked to remove a listener.

Firma:

export declare type Unsubscribe = () => void;