![](/img/trans.png)
[英]Which is a better query for performance using firebase realtime-database
[英]Firebase realtime database query latest 10 records using timestamp key
我在 firebase 实时数据库中有这个集合:
学生:
{
"Mike": {
"Time 2022-08-22 09:04:57": {
"Courses": [
"Maths",
"Chemistry",
"Science"
]
},
"Time 2022-08-15 09:05:58": {
"Courses": [
"Physics",
"Geography",
"Literature"
]
},
"Time 2022-08-15 09:06:59": {
"Courses": [
"Computer Science",
"Biology",
"Chemistry"
]
}
},
"John": {
"Time 2022-08-22 10:04:57": {
"Courses": [
"Maths",
"Chemistry",
"Science"
]
},
"Time 2022-08-15 10:05:58": {
"Courses": [
"Physics",
"Geography",
"Literature"
]
},
"Time 2022-08-15 10:06:59": {
"Data": [
"Computer Science",
"Biology",
"Chemistry"
]
},
"Time 2022-08-15 10:07:59": {
"Courses": [
"Computer Science",
"Biology",
"Physics"
]
}
},
"Steve": {
"Time 2022-08-22 11:01:57": {
"Courses": [
"Maths",
"Chemistry",
"Science"
]
}
}
}
现在在这里我想获取所选学生的最新 2 门课程记录。
到目前为止我尝试的是:
<script src="https://www.gstatic.com/firebasejs/3.2.0/firebase.js"></script>
<script>
var config = {};
firebase.initializeApp(config);
var records = [];
var currentTimestamp = new Date().getTime();
var ref = firebase.database().ref("students/John")
ref.on('value', function(snapshot) {
var records = snapshot.val();
for(var key in records) {
if(currentTimestamp < new Date(key.replace('Time ','')).getTime()){
records.push({
timestamp: key,
arrayRecords: records[key].Courses
});
}
}
});
</script>
现在我需要通过不使用我正在使用的时间戳检查的查询来实现这一点。
要仅获取学生的两门最新课程,您可以执行以下操作:
const ref = firebase.database().ref("students/John")
const query = ref.orderByKey().limitToLast(2);
query.on('value', function(snapshot) {
...
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.