在由孩子订购时使用startAt()进行分页

1 javascript pagination firebase firebase-realtime-database

我试图只检索一个记录列表,按每个记录中的一个字段排序,我希望能够检索页面中的数据.

根据Firebase文档,该reference.startAt()方法有一个可选的第二个参数,它是:

The child key to start at. This argument is only allowed if ordering by child, value, or priority.

首先,这是数据:

{
  "products" : {
    "-KlsqFgVWwUrA-j0VsZS" : {
      "name" : "Product 4",
      "price" : 666
    },
    "-Klst-cLSckuwAuNAJF8" : {
      "name" : "Product 1",
      "price" : 100
    },
    "-Klst7IINdt8YeMmauRz" : {
      "name" : "Product 2",
      "price" : 50
    },
    "-Klst9KfM2QWp8kXrOlR" : {
      "name" : "Product 6",
      "price" : 30
    },
    "-KlstB51ap1L2tcK8cL6" : {
      "name" : "Product 5",
      "price" : 99
    },
    "-KlstDR5cCayGH0XKtZ0" : {
      "name" : "Product 3",
      "price" : 500
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

以下是能够检索第1页的代码(价格最低的商品+第二低价+第三低价):

(我使用的是Firebase JS SDK 4.1.1)

'use strict';
var firebase = require('firebase');

firebase.initializeApp({
    apiKey: "your-api-key",
    authDomain: "your-firebase-domain",
    databaseURL: "https://your-db.firebaseio.com",
    projectId: "your-project",
    storageBucket: "your-bucket.appspot.com",
    messagingSenderId: "your-sender-id"
})

firebase.database().ref('products')
.orderByChild('price')
.limitToFirst(3)
.on('child_added', function (snapshot) {
    var key = snapshot.key;
    var data = snapshot.val();
    console.log(key + ': ' + JSON.stringify(data))
})
Run Code Online (Sandbox Code Playgroud)

输出:

TJ:数据库tjwoon $ node test.js

-Klst9KfM2QWp8kXrOlR: {"name":"Product 6","price":30}
-Klst7IINdt8YeMmauRz: {"name":"Product 2","price":50}
-KlstB51ap1L2tcK8cL6: {"name":"Product 5","price":99}
Run Code Online (Sandbox Code Playgroud)

第2页应该是第三低,第四低和第五低价产品,这意味着我的代码需要一个额外的行:

firebase.database().ref('products')
.orderByChild('price')
.startAt(null, '-KlstB51ap1L2tcK8cL6')
.limitToFirst(3)
.on('child_added', function (snapshot) {
    var key = snapshot.key;
    var data = snapshot.val();
    console.log(key + ': ' + JSON.stringify(data))
})
Run Code Online (Sandbox Code Playgroud)

输出:

TJ:database tjwoon$ node test.js
-Klst9KfM2QWp8kXrOlR: {"name":"Product 6","price":30}
-Klst7IINdt8YeMmauRz: {"name":"Product 2","price":50}
-KlstB51ap1L2tcK8cL6: {"name":"Product 5","price":99}
Run Code Online (Sandbox Code Playgroud)

问题是它再次返回.如果文档是正确的,结果应该从带有密钥的记录开始-KlstB51ap1L2tcK8cL6.

我已经尝试.indexOn为价格字段添加规则,但结果仍然相同.

如果我删除该orderByChild()行,那么结果会从给定的键开始,但当然排序是不正确的,而且它的行为与文档相反......

我发现这些其他Stack Overflow帖子描述了同样的问题:

然而,这些问题没有答案,反应也很少.Github存储库中没有与搜索词匹配的问题startat.

还有其他人面临同样的问题吗?此问题使得无法以分页方式检索已排序的列表...

Fra*_*len 5

你快到了!

问题在于你如何调用startAt第二页:

.startAt(null, '-KlstB51ap1L2tcK8cL6')
Run Code Online (Sandbox Code Playgroud)

要获得正确的结果,您需要传递所谓锚项的价格和密钥:

.startAt(99, '-KlstB51ap1L2tcK8cL6')
Run Code Online (Sandbox Code Playgroud)

随着Firebase将找到所有项目,price 99然后从键返回项目'-KlstB51ap1L2tcK8cL6'.