问题描述
我需要从Firebase集合中获取第一个元素,然后将其删除,但无法弄清楚该如何做。 我需要它来实现云功能。
await ref
.doc(ref.limit(1).get().docs[0]);
1楼
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;
}
});
2楼
您需要在所需元素上调用delete()方法。
Firebase集合不是有序数据类型,因此没有“第一个元素”这样的概念。
但是您可以add()一些标志(例如,时间戳记)以区分首先添加了哪个元素。
Firebase集合本身没有任何内置标志来将元素检测为“第一”。
例如,如果您有时间戳标记:
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事件并将其删除。
另外,如果您需要使用它来实现云功能,请注意value事件。
您需要将第三步更改为以下代码;
collectionLast.once('value', function(snapshot) {
var updates = {};
snapshot.forEach(function(child) {
updates[child.key] = null
});
return ref.update(updates);
});
有关更多信息,您可以获取文档: :