最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get First Element from Collection and delete it - Stack Overflow

programmeradmin1浏览0评论

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]);

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]);
Share Improve this question edited Mar 13, 2023 at 10:43 Renaud Tarnec 83.1k10 gold badges97 silver badges129 bronze badges Recognized by Google Cloud Collective asked Feb 13, 2019 at 9:22 filipfilip 7002 gold badges11 silver badges32 bronze badges 5
  • what data structure is considered under 'Collection'? please provide some example of the data you deal with – bohkoval Commented Feb 13, 2019 at 9:27
  • Do you want it to be deleted from javascript collection (array,object). then you can try this collection.shift(); collection - here is array. – somsgod Commented Feb 13, 2019 at 9:27
  • Meant a Firebase collection @bohkoval – filip Commented Feb 13, 2019 at 9:28
  • You need to define what is the "first" element. Documents in a collection don't have an order other than what you choose, based on the values of fields you add. – Doug Stevenson Commented Feb 13, 2019 at 9:37
  • So I have to get the document Id from the first element? How do I do this? – filip Commented Feb 13, 2019 at 9:41
Add a comment  | 

2 Answers 2

Reset to default 30

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();
});
  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

发布评论

评论列表(0)

  1. 暂无评论