query orderbykey limittolast last item child_added child changed firebase

limittolast - orderbykey firebase



Firebase child_added only get child added (5)

De la API de Firebase:

Niño agregado: Este evento se activará una vez para cada niño inicial en esta ubicación, y se activará nuevamente cada vez que se agregue un niño nuevo.

Cierto código:

listRef.on(''child_added'', function(childSnapshot, prevChildName) { // do something with the child });

Pero dado que la función se llama una vez para cada niño en esta ubicación , ¿hay alguna forma de obtener solo el niño que realmente se agregó?


Como llamar al método ref.push() sin datos genera claves de ruta en función del tiempo, esto es lo que hice:

// Get your base reference const messagesRef = firebase.database().ref().child("messages"); // Get a firebase generated key, based on current time const startKey = messagesRef.push().key; // ''startAt'' this key, equivalent to ''start from the present second'' messagesRef.orderByKey().startAt(startKey) .on("child_added", (snapshot)=>{ /*Do something with future children*/} );

Tenga en cuenta que nada se escribe realmente en la referencia (o ''clave'') que ref.push() devolvió, por lo que no es necesario capturar datos vacíos.


Intenté otras respuestas, pero invoqué al menos una vez al último hijo. Si tiene una clave de tiempo en sus datos, puede hacerlo de esta manera.

ref.orderByChild(''createdAt'').startAt(Date.now()).on(''child_added'', ...


Para rastrear cosas agregadas desde algún punto de control sin obtener registros previos, puede usar endAt() y limit() para tomar el último registro:

// retrieve the last record from `ref` ref.endAt().limit(1).on(''child_added'', function(snapshot) { // all records after the last continue to invoke this function console.log(snapshot.name(), snapshot.val()); });


Solución Swift3:

Puede recuperar sus datos anteriores a través del siguiente código:

queryRef?.observeSingleEvent(of: .value, with: { (snapshot) in //Your code })

y luego observe los nuevos datos a través del siguiente código.

queryRef?.queryLimited(toLast: 1).observe(.childAdded, with: { (snapshot) in //Your Code })


limit() método limit() está en desuso. limitToLast() y limitToFirst() reemplazan.

// retrieve the last record from `ref` ref.limitToLast(1).on(''child_added'', function(snapshot) { // all records after the last continue to invoke this function console.log(snapshot.name(), snapshot.val()); // get the last inserted key console.log(snapshot.key()); });