javascript - 过滤firebase数据库中的数据时遇到问题
问题描述
我正在尝试从云功能中的 firebase 数据库中过滤一些数据。该数据如下所示:
"items": {
"id1": {
"status": {
"creation": timestampValue,
"status": "initialized"
},
"data" : data1
}
"id2": {
"status": {
"status": "loaded"
},
"data" : data2
},
"id2": {
"status": {
"creation": timestampValue,
"status": "loaded"
},
"data" : data
},
"id3": {
"status": {
"creation": timestampValue,
"status": "ended"
},
"data" : data3
}
}
我想使用基于创建字段的过滤器。该字段并不总是存在。
我的代码受此启发: https ://github.com/firebase/functions-samples/blob/master/delete-old-child-nodes/functions/index.js
这是我写的代码:
const CUT_OFF_TIME = 24 * 60 * 60 * 1000; // 24 Hours in milliseconds.
exports.cleanAfter24h = functions.database.ref('/items/{itemId}').onUpdate((change, event) => {
const ref = change.after.ref.parent; // reference to the parent
const now = Date.now();
const cutoff = now - CUT_OFF_TIME;
const oldItemsQuery = ref.orderByChild('creation').endAt(cutoff);
return oldItemsQuery.once('value').then((snapshot) => {
// create a map with all children that need to be removed
const updates = {};
snapshot.forEach(child => {
let childData = child.val();
if (childData.status.creation) {
let elapsed = childData.status.creation - cutoff;
if (elapsed <= 0) {
updates[child.key] = null;
}
} else {
console.log(child.key + ' does not have a creation date');
}
});
// execute all updates in one go and return the result to end the function
return ref.update(updates);
});
});
运行代码时,将检索所有项目,甚至包括时间戳小于截止值的项目和没有创建字段的项目。有什么建议可以解决这个问题吗?
我尝试按照此处的建议通过在 endAt 之前添加 startAt("") 来删除没有创建字段的项目: Firebase,以“一个孩子存在”作为条件进行查询?
const oldItemsQuery = ref.orderByChild('creation')startAt("").endAt(cutoff);
这样做我在查询响应中没有结果。
解决方案
改变这个:
const oldItemsQuery = ref.orderByChild('creation').endAt(cutoff);
进入这个:
const oldItemsQuery = ref.orderByChild('creation').equalTo(cutoff);
创建一个包含与指定值匹配的子项的 Query。
使用
startAt()
、endAt()
和equalTo()
允许我们为查询选择任意起点和终点。
推荐阅读
- javascript - 如何编辑网站 HTML,然后在您重新加载时让它在那里,但只为您服务?
- scala - Spark/Scala:如何获得前 X % 的行?
- php - Import library of php to laravel project
- python - Python CFFI:从多个源文件构建单个模块
- express - 使用 Koa 和 Express 调用 API 的区别
- heroku - procfile 没有从 web 更改为 worker
- java - 使用 Spring MVC 提供静态内容和渲染 JSP
- javascript - 动态绑定图像Angular 8
- excel - Excel VBA 将日期翻译成另一种格式
- apollo - 在 nextJS 上配置 apollo 客户端以进行订阅的问题