首页 文章

无法过滤firebase数据库中的数据

提问于
浏览
2

我正在尝试从 Cloud 功能中过滤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, query with "a child exists" as a condition?

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

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

1 回答

  • 0

    改变这个:

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

    进入这个:

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

    equalTo创建一个包含与指定值匹配的子项的查询 . 使用startAt(),endAt()和equalTo()允许我们为查询选择任意的起点和终点 .

相关问题