如何结合Firestore orderBy和startAfter光标

use*_*046 6 javascript firebase google-cloud-firestore react-native-firebase

我正在尝试查询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()
Run Code Online (Sandbox Code Playgroud)

use*_*046 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();
Run Code Online (Sandbox Code Playgroud)


Fra*_*len 5

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

db.collection('tanks')
  .doc(tankId)
  .collection('documentations')
  .orderBy('date', 'desc')
  .startAfter(lastDoc)
  .limit(pageSize)
  .get()
Run Code Online (Sandbox Code Playgroud)

请参阅参考文档startAfter()