繁体   English   中英

我刚开始使用 firebase 并在获取数据时遇到 orderBy desc function 问题

[英]I just started with firebase and have problem with orderBy desc function when getting data

在function orderBy中传“desc”参数时不返回数据,但传“asc”或空白时有数据。

const getListProduct = async () => {
    const products = await fs
      .collection("products")
      .orderBy("createAt", "desc") //problem is here.It just works orderBy("createAt", "asc") or orderBy("createAt")
      .startAfter(0)
      .limit(5)
      .get();
    let listProduct = [];

    for (let snap of products.docs) {
      let data = snap.data();
      data.ID = snap.id;
      listProduct.push({ id: snap.id, ...data });
      if (products.docs.length === listProduct.length) {
        
        setListData(listProduct);
      }
    }
  };
     

startAfter()中的值必须是DocumentSnapshot或要在之后开始此查询的字段的值。 如果createAt字段是时间戳,那么它必须是startAfter(<DATE_OBJ>)或上次查询的文档快照,但您传递的是一个数字。 尝试重构代码,如下所示:

const products = await fs
  .collection("products")
  .orderBy("createAt", "desc")
  .startAfter(new Date(2022, 8, 17, 6, 54, 0)) // for testing Date(year, date, month, hh, mm, ss)
  .limit(5)
  .get();

这应该按降序返回startAfter小于提供的时间戳的所有产品。


或者,您可以将最后一个查询的快照存储在 state 中并使用它,如下所示:
 let lastSnapshot = null; const q = fs.collection("products").orderBy("createAt", "desc") if (lastSnapshot) { // Query has been executed before, use last snapshot q.startAfter(lastSnapshot); } const products = await q.limit(5).get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM