Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get First Element from Collection and delete it

I need to get the first element from a Firebase Collection and then delete it, but can't figure out how to do it. I need it for a cloud function.

await ref
      .doc(ref.limit(1).get().docs[0]);
like image 309
filip Avatar asked Feb 13 '19 09:02

filip


2 Answers

Bohkoval's overall logic, as presented in his/her answer is correct, however the answer is related to the Realtime Database, while the OP is working with Firestore (from the tags used in his question).

Making the assumption that you "have a timestamp property which [you] can sort by" as you said in the comment below, in a Cloud Function you would do as follows for Firestore:

return admin.firestore().collection("yourCollection")
.orderBy("yourTimestamp", "desc")
.limit(1)
.get()
.then(querySnapshot => {
    if (!querySnapshot.empty) {
        //We know there is one doc in the querySnapshot
        const queryDocumentSnapshot = querySnapshot.docs[0];
        return queryDocumentSnapshot.ref.delete();
    } else {
        console.log("No document corresponding to the query!");
        return null;
    }
});
like image 144
Renaud Tarnec Avatar answered Nov 06 '22 12:11

Renaud Tarnec


You need to call delete() method on the desired element.

Firebase collection is not ordered data type, so there is no such notion as "first element". But you can add() some flag (for example, a timestamp) in order to distinguish which element was added firstly. Firebase collection itself doesn't have any built-in flag to detect an element as "first".

For example, if you have timestamp flag:

var collection = firebase.database().ref('/path/to/collection');
var collectionLast = collection.orderByChild('timestamp').limit(1);
var listener = collectionLast.on('child_added', function(snapshot) {
    snapshot.ref.remove();
});
  1. get collection reference
  2. order elements by timestamp (it will be done in ascending order), limit to first element
  3. when this element is retrieved from the collection, child_added event is triggered with the snapshot payload and remove it.

Also, if you need it for cloud function, pay attention to value event. You need to change 3rd step to the following code;

collectionLast.once('value', function(snapshot) {
    var updates = {};
    snapshot.forEach(function(child) {
      updates[child.key] = null
    });
    return ref.update(updates);
  });

For more info you can grab the doc: https://firebase.google.com/docs/database/admin/retrieve-data

like image 23
bohkoval Avatar answered Nov 06 '22 11:11

bohkoval