14

我正在尝试查询 firestore 中的列表,该列表应按降序日期属性排序,并使用 startAfter 光标对结果进行分页。

正如您在下面的片段中看到的那样,一旦我将 orderBy('date', 'desc') 与 startAfter(lastDoc.date) 结合使用,这将失败。

我想知道我做错了什么。有任何想法吗?

// this actually works
// but it is sorted by ascending dates
db.collection('tanks')
  .doc(tankId)
  .collection('documentations')
  .orderBy('date')
  .startAfter(lastDoc.date)
  .limit(pageSize)
  .get()
  
// this even works...
// but has no cursor (startAfter) set for pagination
db.collection('tanks')
  .doc(tankId)
  .collection('documentations')
  .orderBy('date', 'desc')
  .limit(pageSize)
  .get()
  
// this is what i need
// but it returns always zero results
db.collection('tanks')
  .doc(tankId)
  .collection('documentations')
  .orderBy('date', 'desc')
  .startAfter(lastDoc.date)
  .limit(pageSize)
  .get()

4

2 回答 2

13

您需要将实际文档快照传递给startAfter,而不是日期值:

db.collection('tanks')
  .doc(tankId)
  .collection('documentations')
  .orderBy('date', 'desc')
  .startAfter(lastDoc)
  .limit(pageSize)
  .get()

请参阅参考文档startAfter()

于 2018-01-04T15:19:59.323 回答
6

这实际上有效,不知道为什么以前没有...

const snapshot = lastDoc
  ? await Api.db.collection('tanks')
      .doc(tankId)
      .collection('documentations')
      .orderBy('date', 'desc')
      .startAfter(lastDoc.date)
      .limit(pageSize)
      .get()
  : await Api.db.collection('tanks')
      .doc(tankId)
      .collection('documentations')
      .orderBy('date', 'desc')
      .limit(pageSize)
      .get();

于 2018-01-04T15:52:29.170 回答