我只想检索最近 2 天的数据。为此,我将日期作为位置的子项插入。这就是我的数据库的样子:
如您所见,我将日期插入到第三级以及第四级数据中。
我尝试使用 .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 (第四级)。
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.
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/