javascript - 从 Firebase 数据库检索过去 2 天的结果

标签 javascript firebase-realtime-database

我只想检索最近 2 天的数据。为此,我将日期作为位置的子项插入。这就是我的数据库的样子:

enter image description here

如您所见,我将日期插入到第三级以及第四级数据中。

我尝试使用 .startAt(Date.now() - 5 * 60 * 60 * 1000); 但它不起作用,因为它返回了我 null结果。

readLocations = () => {
    // console.warn("readlocations called");
    allLocations = [];
    let locations = firebase
      .database()
      .ref("/locations")
      .child(this.currentUser.uid)
    .startAt(Date.now() - 5 * 60 * 60 * 1000);
    locations.on("value", snapshot => {
      console.log(snapshot)
    });
  };

这就是我将数据插入数据库的方式。

  sendLocation = () => {
    // console.log("sending location log", this.props);
    firebase
      .database()
      .ref("/locations")
      .child(this.currentUser.uid)
      .child(Date.now())
      .set({
        uid: this.currentUser.uid,
        user: user,
        latitude: this.props.location.coords.latitude,
        longitude: this.props.location.coords.longitude,
        created_at: Date.now()
      });
  };

最佳答案

您需要确保在使用 startAt、endAt、equalTo 之前对数据进行排序。

参见Filtering data来自文档和 API reference

startAt() return items greater than or equal to the specified key or value, depending on the order-by method chosen.


根据您的情况,您可以使用 orderByKey (第三级)或orderByChild (第四级)。

  1. orderByKey

    const _2daysago = Date.now() - (2 * 24 * 60 * 60 * 1000);
    
    const query = firebase.database()
      .ref("/locations")
      .child(this.currentUser.uid)
      .orderByKey()
      // value must be a string (not a number)
      .startAt(String(_2daysago));
    

    When startAt is used in combination with orderByKey(), the value must be a string.

    参见startAt - Parameters

  2. orderByChild

    const _2daysago = Date.now() - (2 * 24 * 60 * 60 * 1000);
    
    const query = firebase.database()
      .ref("/locations")
      .child(this.currentUser.uid)
      // no need to convert to a string
      .orderByChild('created_at')
      .startAt(_2daysago);
    

    注意:您将在控制台中收到一条警告,鼓励您在created_at上定义索引以提高性能(请参阅Indexing with orderByChild)。

您可以在 StackBlitz 上尝试以上操作。只需 fork 该项目并添加您的 Firebase 配置即可。

关于javascript - 从 Firebase 数据库检索过去 2 天的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59191301/

相关文章:

javascript - GET 请求抛出错误 : str. replace is not a function

java - 获得具有特定值(value)的所有 child 的最简单方法是什么

android - 如何从android中的firebase中检索List对象

javascript - jQuery 点击事件触发两次

javascript - Vue.js 中的条件逻辑

javascript - 创建这个 javascript 和 css 繁重的元素的最有效方法是什么?

android - Firebase 数据库不检索数据

Firebase 数据库 getInstance 导致应用程序崩溃

javascript - FRebase "pushing"数组对象不起作用

javascript - 在 Firefox 中将日期字符串转换为日期对象时出错