如何在一定范围内查询实时数据库
How to query Realtime Database between a certain range
我正在使用 Next.js 和 Firestore 实时数据库 (v9.x) 实现无限滚动。
当客户端请求主页时,服务器从数据库中获取最近的4张图像并显示给客户端。当用户到达页面底部时,应该再获取 4 张图像,依此类推。
这是我的数据库:
每次用户添加新图片时,该图片都会被推到列表的末尾,就像 array/list.
对于在服务器端获取并 sent/displayed 到客户端的前 4 个图像,我使用此代码:
query(ref(db, 'latest_images'), limitToLast(4))
此代码旨在获取最后添加的四张图片(最新图片)。
现在,在客户端,当用户到达页面末尾时,这是我用来获取另外 4 张图片的代码:
query(
ref(db, `latest_images`),
endBefore(lastImageID), // lastImagedID = "-MqZdzr7RTYpyujV6hnP" (w/ d. quotes)
limitToLast(4),
)
lastImageID
存储的是上图数据库中从下往上第四个入口key。这个变量是一个“锚点”,因此代码知道从哪里开始查询接下来的 4 张图像。
我对上面的代码的预期是它会获取这些图像(由红色大括号分隔):
但它最终获取了与最初在服务器端获取的相同的 4 张图像(由蓝色大括号分隔)。
来自纪录片:
endBefore() Return items less than the specified key or value depending on the order-by method chosen.
limitToLast() Sets the maximum number of items to return from the end of the ordered list of results.
https://firebase.google.com/docs/database/web/lists-of-data?authuser=0#filtering_data
正如我们在评论中讨论的那样,您必须先告诉数据库要订购什么,然后才能过滤数据。由于您正在过滤键,因此将 orderByKey()
添加到您的查询将确保它知道要过滤键。
我已经提交了一个错误以在文档片段中对此进行澄清,因为现在很容易误解它。
我正在使用 Next.js 和 Firestore 实时数据库 (v9.x) 实现无限滚动。
当客户端请求主页时,服务器从数据库中获取最近的4张图像并显示给客户端。当用户到达页面底部时,应该再获取 4 张图像,依此类推。
这是我的数据库:
每次用户添加新图片时,该图片都会被推到列表的末尾,就像 array/list.
对于在服务器端获取并 sent/displayed 到客户端的前 4 个图像,我使用此代码:
query(ref(db, 'latest_images'), limitToLast(4))
此代码旨在获取最后添加的四张图片(最新图片)。
现在,在客户端,当用户到达页面末尾时,这是我用来获取另外 4 张图片的代码:
query(
ref(db, `latest_images`),
endBefore(lastImageID), // lastImagedID = "-MqZdzr7RTYpyujV6hnP" (w/ d. quotes)
limitToLast(4),
)
lastImageID
存储的是上图数据库中从下往上第四个入口key。这个变量是一个“锚点”,因此代码知道从哪里开始查询接下来的 4 张图像。
我对上面的代码的预期是它会获取这些图像(由红色大括号分隔):
但它最终获取了与最初在服务器端获取的相同的 4 张图像(由蓝色大括号分隔)。
来自纪录片:
endBefore() Return items less than the specified key or value depending on the order-by method chosen.
limitToLast() Sets the maximum number of items to return from the end of the ordered list of results.
https://firebase.google.com/docs/database/web/lists-of-data?authuser=0#filtering_data
正如我们在评论中讨论的那样,您必须先告诉数据库要订购什么,然后才能过滤数据。由于您正在过滤键,因此将 orderByKey()
添加到您的查询将确保它知道要过滤键。
我已经提交了一个错误以在文档片段中对此进行澄清,因为现在很容易误解它。