Firebase实时数据库和HTTP请求:跨多个轴的复杂查询

时间:2018-11-19 17:21:07

标签: javascript firebase firebase-realtime-database

我有以下代码来检索具有给定日期和小时范围内的时间戳的数据:

app.get('/mymeals/filtered', async(req,res) => {
    let dayFrom= req.query.dayFrom;
    let dayTo= req.query.dayTo;
    let hourFrom= req.query.hourFrom;
    let hourTo= req.query.hourTo;
    console.log(`${dayFrom}-${dayTo} ${hourFrom} ${hourTo}`);
    let userId= req.user.uid;
    return await dbroot.ref(`duplicates/${userId}`)
        .orderByKey().startAt(`${dayFrom}`).endAt(`${dayTo}`).once('value').then( (snapshot) => {
            console.log(snapshot.val());
            return snapshot.ref.orderByKey().startAt(`${hourFrom}`).endAt(`${hourTo}`).once('value').then( (s) => {
                console.log(s.val());
                return res.status(200).send(s.val());
            });
        })
});

有问题的数据库如下所示: enter image description here

也就是说,为了便于检索,我首先按日期对项目进行分类,然后在日期范围内按小时进行分类。因此,上图中的1212:00PM。 现在,Firebase不允许链接两个orderByKey(),这就是为什么我尝试先按日期查询,然后给定快照,尝试使用snapshot.forEach(child)遍历子级的原因,如下所示:

    app.get('/mymeals/filtered', async(req,res) => {
    let dayFrom= req.query.dayFrom;
    let dayTo= req.query.dayTo;
    let hourFrom= req.query.hourFrom;
    let hourTo= req.query.hourTo;
    console.log(`${dayFrom}-${dayTo} ${hourFrom} ${hourTo}`);
    let userId= req.user.uid;
    return await dbroot.ref(`duplicates/${userId}`)
        .orderByKey().startAt(`${dayFrom}`).endAt(`${dayTo}`).once('value').then( (snapshot) => {
            console.log(snapshot.val());
            acc= [];
            snapshot.forEach( (day) => {
                day.forEach((hour) => {
                    console.log("This: " + hour.key);
                    if (hourFrom <= hour.key && hour.key <= hourTo)
                        hour.forEach((meal) => {
                            acc.push(meal.val());
                        });
                });
            });
            return res.status(200).send(acc);
        })
});

我的问题是,仍然可以沿两个轴以某种方式链接查询,还是唯一的方法类似于第二个代码片段?

0 个答案:

没有答案