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]);
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;
}
});
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();
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With