首页 > 解决方案 > 过滤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);

这样做我在查询响应中没有结果。

标签: javascriptfirebasefirebase-realtime-databasegoogle-cloud-functions

解决方案


改变这个:

const oldItemsQuery = ref.orderByChild('creation').endAt(cutoff);

进入这个:

const oldItemsQuery = ref.orderByChild('creation').equalTo(cutoff);

equalTo

创建一个包含与指定值匹配的子项的 Query。

使用startAt()endAt()equalTo()允许我们为查询选择任意起点和终点。


推荐阅读