Firestore分页 - 是否有任何与firebase的limitToLast兼容的查询?

时间:2018-01-19 13:44:50

标签: sorting firebase pagination google-cloud-firestore

有没有办法用firestore实现反分页? 我正在努力实现与firestore的分页,并且对它的firestore查询有限。可以通过 startAt 限制方法进行前向分页,即可。但是后面的分页可以轻松完成,因为我们只有 endBefore endAt 方法,我们怎样才能获得最后的 n 给定文件中的元素?我知道实时数据库有方法 limitToLast 。对于firestore有这样的查询吗? (另外我需要实现多重排序,因此使用" ASC"或" DESC"排序将无效)获取最后一个文档 非常感谢。

谢谢!

5 个答案:

答案 0 :(得分:4)

与Cloud Firestore中Firebase实时数据库的limitToLast(...)操作相当的是对数据进行降序排序(可以在Firestore中进行),然后只需limit(...)。如果您在实施此问题时遇到问题,请更新您的问题以显示您已完成的工作。

我同意这是用于反向分页的次优API,因为您以相反的顺序接收这些项目。

答案 1 :(得分:1)

更简单的答案:Firestore现在具有.limitToLast(),其功能完全符合您的想象。在我自己的容器中使用(猜测我需要尽快发布)Firestore Wrapper:

//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// *** Paginate API ***

export const PAGINATE_INIT = 0;
export const PAGINATE_PENDING = -1;
export const PAGINATE_UPDATED = 1;
export const PAGINATE_DEFAULT = 10;
export const PAGINATE_CHOICES = [10, 25, 50, 100, 250, 500];

/**
 * @classdesc
 * An object to allow for paginating a table read from Firestore. REQUIRES a sorting choice
 * @property {Query} Query that forms basis for the table read
 * @property {number} limit page size
 * @property {QuerySnapshot} snapshot last successful snapshot/page fetched
 * @property {enum} status status of pagination object
 * @method PageForward pages the fetch forward
 * @method PageBack pages the fetch backward
 */

export class PaginateFetch {
  Query = null;
  limit = PAGINATE_DEFAULT;
  snapshot = null;
  status = null; // -1 pending; 0 uninitialize; 1 updated;
  /**
   * ----------------------------------------------------------------------
   * @constructs PaginateFetch constructs an object to paginate through large
   * Firestore Tables
   * @param {string} table a properly formatted string representing the requested collection
   * - always an ODD number of elements
   * @param {array} filterArray an (optional) 3xn array of filter(i.e. "where") conditions
   * @param {array} sortArray a 2xn array of sort (i.e. "orderBy") conditions
   * @param {ref} ref (optional) allows "table" parameter to reference a sub-collection
   * of an existing document reference (I use a LOT of structered collections)
   *
   * The array is assumed to be sorted in the correct order -
   * i.e. filterArray[0] is added first; filterArray[length-1] last
   * returns data as an array of objects (not dissimilar to Redux State objects)
   * with both the documentID and documentReference added as fields.
   * @param {number} limit (optional)
   * @returns {PaginateFetchObject}
   **********************************************************************/

  constructor(
    table,
    filterArray = null,
    sortArray = null,
    ref = null,
    limit = PAGINATE_DEFAULT
  ) {
    const db = ref ? ref : fdb;

    this.limit = limit;
    this.Query = sortQuery(
      filterQuery(db.collection(table), filterArray),
      sortArray
    );
    this.status = PAGINATE_INIT;
  }

  /**
   * @method Page
   * @returns Promise of a QuerySnapshot
   */
  PageForward = () => {
    const runQuery = this.snapshot
      ? this.Query.startAfter(_.last(this.snapshot.docs))
      : this.Query;

    this.status = PAGINATE_PENDING;

    return runQuery
      .limit(this.limit)
      .get()
      .then((QuerySnapshot) => {
        this.status = PAGINATE_UPDATED;
        //*IF* documents (i.e. haven't gone beyond start)
        if (!QuerySnapshot.empty) {
          //then update document set, and execute callback
          //return Promise.resolve(QuerySnapshot);
          this.snapshot = QuerySnapshot;
        }
        return this.snapshot.docs.map((doc) => {
          return {
            ...doc.data(),
            Id: doc.id,
            ref: doc.ref
          };
        });
      });
  };

  PageBack = () => {
    const runQuery = this.snapshot
      ? this.Query.endBefore(this.snapshot.docs[0])
      : this.Query;

    this.status = PAGINATE_PENDING;

    return runQuery
      .limitToLast(this.limit)
      .get()
      .then((QuerySnapshot) => {
        this.status = PAGINATE_UPDATED;
        //*IF* documents (i.e. haven't gone back ebfore start)
        if (!QuerySnapshot.empty) {
          //then update document set, and execute callback
          this.snapshot = QuerySnapshot;
        }
        return this.snapshot.docs.map((doc) => {
          return {
            ...doc.data(),
            Id: doc.id,
            ref: doc.ref
          };
        });
      });
  };
}

/**
 * ----------------------------------------------------------------------
 * @function filterQuery
 * builds and returns a query built from an array of filter (i.e. "where")
 * consitions
 * @param {Query} query collectionReference or Query to build filter upong
 * @param {array} filterArray an (optional) 3xn array of filter(i.e. "where") conditions
 * @returns Firestor Query object
 */
export const filterQuery = (query, filterArray = null) => {
  return filterArray
    ? filterArray.reduce((accQuery, filter) => {
        return accQuery.where(filter.fieldRef, filter.opStr, filter.value);
      }, query)
    : query;
};

/**
 * ----------------------------------------------------------------------
 * @function sortQuery
 * builds and returns a query built from an array of filter (i.e. "where")
 * consitions
 * @param {Query} query collectionReference or Query to build filter upong
 * @param {array} sortArray an (optional) 2xn array of sort (i.e. "orderBy") conditions
 * @returns Firestor Query object
 */
export const sortQuery = (query, sortArray = null) => {
  return sortArray
    ? sortArray.reduce((accQuery, sortEntry) => {
        return accQuery.orderBy(sortEntry.fieldRef, sortEntry.dirStr || "asc");
        //note "||" - if dirStr is not present(i.e. falsy) default to "asc"
      }, query)
    : query;
};

对于CollectionGroup查询,我也具有等效功能;对于每个查询,也具有侦听器。

答案 2 :(得分:0)

我遇到了同样的问题,但不理解为什么将limitendAt一起使用并没有返回我想要的结果。我正在尝试实现一个列表,在该列表中您可以在两个方向上分页,首先向前然后向后返回列表的开头。

为解决这种情况,我决定只为每个页面缓存startAfter DocumentSnapshot,以便一个人可以同时移动两个方向,这样我就不必使用endAt。唯一会成为问题的是,如果文档集合在用户位于第一页以外的页面上时发生移动或更改,但是如果返回到第一页,它将重置为集合的开始。

答案 3 :(得分:0)

是的。以弗兰克的答案为基础...

查询中有类似的内容...

    if (this.next) {
      // if next, orderBy field descending, start after last field
      q.orderBy('field', 'desc');
      q.startAfter(this.marker);
    } else if (this.prev) {
      // if prev, orderBy field ascending, start after first field
      q.orderBy('field', 'asc');
      q.startAfter(this.marker);
    } else {
      // otherwise just display first page results normally
      q.orderBy('field', 'desc');
    }
    q.limit(this.pageSize);

然后在查询时将其反转...

    this.testsCollection
            .valueChanges({ idField: 'id' })
            .pipe(
              tap(results => {
                if (this.prev) {
                  // if previous, need to reverse the results...
                  results.reverse();
                }
              })
            )

答案 4 :(得分:0)

我只想分享我的Firestore分页代码。
我正在使用带有NextJS的React钩子。

您将需要具有“ useFirestoreQuery”钩子,可在此处找到。
Rationale and list of changes for XML 1.1

这是我的设置。

/* Context User */
const {user} = useUser()

/* States */
const [query, setQuery] = useState(null)
const [ref, setRef] = useState(null)
const [reverse, setReverse] = useState(false)
const [limit, setLimit] = useState(2)
const [lastID, setLastID] = useState(null)
const [firstID, setFirstID] = useState(null)
const [page, setPage] = useState(1)

/* Query Hook */
const fireCollection = useFirestoreQuery(query)

/* Set Ref, **When firebase initialized** */
useEffect(() => {
  user?.uid &&
    setRef(
      firebase
        .firestore()
        .collection('products')
        .where('type', '==', 'vaporizers')
    )
}, [user])

/* Initial Query, **When ref set** */
useEffect(() => {
  ref && setQuery(ref.orderBy('id', 'asc').limit(limit))
}, [ref])

/* Next Page */
const nextPage = useCallback(() => {
  setPage((p) => parseInt(p) + 1)
  setReverse(false)
  setQuery(ref.orderBy('id', 'asc').startAfter(lastID).limit(limit))
}, [lastID, limit])

/* Prev Page */
const prevPage = useCallback(() => {
  setPage((p) => parseInt(p) - 1)
  setReverse(true)
  setQuery(ref.orderBy('id', 'desc').startAfter(firstID).limit(limit))
}, [firstID, limit])

/* Product List */
const ProductList = ({fireCollection}) => {
  const [products, setProducts] = useState([])

  useEffect(() => {
    let tempProducts = []
    let tempIDs = []
    const {data} = fireCollection
    for (const key in data) {
      const product = data[key]
      tempIDs.push(product.id)
      tempProducts.push(<ProductRow {...{product}} key={key} />)
    }
    if (reverse) {
      tempProducts.reverse()
      tempIDs.reverse()
    }
    setFirstID(tempIDs[0])
    setLastID(tempIDs.pop())
    setProducts(tempProducts)
  }, [fireCollection])

  return products
}

我使用上下文提供程序将“ ProductList”移出了组件之外,但这是它的要旨。


注意。 如果您正在寻找产品总数。我建议您通过这些云功能跟上总数。您将需要将总计存储在单独的集合中。我称我为“捷径”。

exports.incrementProducts = functions.firestore
  .document('products/{id}')
  .onCreate(async (snap, context) => {
    const createdProduct = snap.data()
    /* Increment a shortcut collection that holds the totals to your products */
  })

exports.decrementProducts = functions.firestore
  .document('products/{id}')
  .onDelete((snap, context) => {
    const deletedProduct = snap.data()
    /* Decrement a shortcut collection that holds the totals to your products */
  })

https://usehooks.com/useFirestoreQuery/



别忘了
确保为所有这些设置索引。这是我的样子。

enter image description here