从集合中获取第一个元素并将其删除

fil*_*lip 2 javascript firebase google-cloud-functions google-cloud-firestore

我需要从Firebase集合中获取第一个元素,然后将其删除,但无法弄清楚该如何做。我需要它来实现云功能。

await ref
      .doc(ref.limit(1).get().docs[0]);
Run Code Online (Sandbox Code Playgroud)

Ren*_*nec 6

Bohkoval的总体逻辑(正确答案是正确的),但是答案与Realtime Database有关,而OP正在使用Firestore(根据他的问题中使用的标签)。

如您在下面的注释中所述,假设您“具有[可以按[排序]的时间戳记属性],在Cloud Function中,您将对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;
    }
});
Run Code Online (Sandbox Code Playgroud)