Firebase按键节点排序/过滤

时间:2017-02-20 19:02:39

标签: javascript firebase firebase-realtime-database relationship nosql

{
"places": {
    "<push-key>": {
        "name": "Company X"
    },
    "<push-key>": {
        "name": "Restaurant Y"
    }
}
"stamps": {
    "<push-key>": {
        "value": 0,
        "date": 1487344650456
    }
},
"placeStamps": {
    "<place-push-key>": {
        "<stamp-push-key-1>": true,
        "<stamp-push-key-2>": true,
        "<stamp-push-key-3>": true
    }
}
}

我们是Firebase的新手,我们想知道是否有办法按日期对邮票(数据库中的节点)进行排序。我们的流程如下:

  • 我们使用places节点检索我们想要的地方。
  • 使用该位置的键,我们从placeStamps / node中检索印章键。
  • 然后我们从邮票节点逐个检索邮票。

有没有办法按例如'date'或'value'对这些对象进行排序/过滤?我们无法做客户端,因为我们正在讨论数以百万计的邮票。

1 个答案:

答案 0 :(得分:0)

自24小时前查询邮票:

var ref = firebase.database.ref("stamps");
var now = Date.now();
var yesterday = now - 24 * 60 * 60 * 1000;
var query = ref.orderByChild("Date").startAt(yesterday);
query.on("child_added", function(snapshot) {
    console.log(snapshot.key);
});

如果您想按时间戳检索某个地方的图章,您有两种选择:

  • 检索该地点的邮票,并按时间戳客户端订购。由于Firebase会对请求进行管道处理,因此检索多个项目并不像您预期​​的那么慢。见Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly
  • 为每个地方的戳记键添加时间戳:

    placeStamps": {
      "<place-push-key>": {
        "<stamp-push-key-1>": 1487344650456,
        "<stamp-push-key-2>": 1487344650457,
        "<stamp-push-key-3>": 1487344650458
      }
    }
    

    现在你可以通过时间戳获得一个地方的邮票:

    var ref = firebase.database.ref("placeStamps").child("<place-push-key>");
    var now = Date.now();
    var yesterday = now - 24 * 60 * 60 * 1000;
    var query = ref.orderByValue().startAt(yesterday);