Firebase实时数据库JavaScript查询

huangapple go评论60阅读模式
英文:

Firebase Realtime Database Query in JavaScript

问题

我想在存储在Firebase实时数据库中的数据上实现分页。阅读了一些文档后,我了解到可以使用以下查询函数。

const q = query(
  citiesRef, 
  orderBy("population"), 
  startAt(10000), 
  limitToFirst(10)
);

在这里,我们可以根据 orderBy 键定义 startAt。但是,我没有任何用于 orderBy 的字段,而是想根据键来进行分页。请看下面的数据库结构 -

  • Chapter1
    • Sloka1
      • Sloka
      • Translation
    • Sloka2
      • Sloka
      • Translation
    • Sloka3
      • Sloka
      • Translation
    • Sloka4
      • Sloka
      • Translation

所以基本上,如果您看到我的键是Sloka1、Sloka2等等。那么在这种情况下,我应该如何使用 startAt() 呢?

我尝试过只使用 startAt(),但它给我报错。

我期望它应该返回像 startAt(2) 和 limitToFirst(2) 这样的结果,那么它应该返回 Sloka2 和 Sloka3。

英文:

I want to implement pagination on data stored in firebase realtime database. Reading some documentation I got to know that we can use query function given below.

const q = query(
  citiesRef, 
  orderBy("population"), 
  startAt(10000), 
  limitToFirst(10)
);

where we can define startAt based on orderBy key. But I don't have any field for orderBy instead I want to do pagiantion based on the key.
See the below database structure -

  • Chapter1
    • Sloka1
      • Sloka
      • Translation
    • Sloka2
      • Sloka
      • Translation
    • Sloka3
      • Sloka
      • Translation
    • Sloka4
      • Sloka
      • Translation

So basically if you see my key is Sloka1, Sloka2 etc.. So how can I use startAt() in this condition.

I have tried using startAt() only, but it's giving me error.

I am expecting it should return like if startAt(2) and limitToFirst(2) then it should return Sloka2 and Sloka3.

答案1

得分: 1

你正在寻找的是 orderByKey(),这在数据排序文档中有介绍。一旦按照键排序了数据,然后你可以将一个键传递给 startAt

所以在你提供的示例数据结构中,代码如下:

const q = query(
  citiesRef, 
  orderByKey(), 
  startAt("Sloka2"), 
  limitToFirst(2)
);

这个查询将会给你返回 Sloka2Sloka3 作为结果。

英文:

What you're looking for is orderByKey(), which is covered in the documentation on ordering data. Once you've ordered the data by its keys, you can then pass a key to startAt.

So in the example data structure you gave, that'd be:

const q = query(
  citiesRef, 
  orderByKey(), 
  startAt("Sloka2"), 
  limitToFirst(2)
);

This query will give you Sloka2 and Sloka3 as the results.

huangapple
  • 本文由 发表于 2023年7月4日 20:42:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76612757.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定