【问题标题】:how to use orderByChild with startAfter in Realtime Database using Node.js如何使用 Node.js 在实时数据库中使用 orderByChild 和 startAfter
【发布时间】:2021-11-22 01:23:07
【问题描述】:

我正在尝试按降序对订单进行排序并在特定键之后开始,但它不起作用

nextAfter : -Mk4-n5BnVpwhum62n2g 或任何 Key / _id

数据库记录:

{
  '-Mk4-n5BnVpwhum62n2g': {
    _id: '-Mk4-n5BnVpwhum62n2g',
    createdAt: -1632171667626,
    name: 'abc'
  },
  '-Mk40Ko9DbSeMdjIpY4': {
    _id: '-Mk40Ko9DbSeMdjIpY4',
    createdAt: -1632171809831,    
    name: 'new '
  }
}

尝试查询:

query = dbRef.orderByChild('createdAt').startAfter(nextAfter).limitToFirst(limit);

【问题讨论】:

  • 你能说明nextAfter在哪里定义吗?>
  • in nextAfter我分配了db的Key值
  • 您正在使用orderByChild,因此startAfter 将在 createdAt 字段上工作。
  • 有没有其他方法可以按子排序并在 ID 上使用 startafter

标签: node.js firebase express firebase-realtime-database


【解决方案1】:

startAfter() method 接受两个参数 - 第一个是相关的 orderBy 值,第二个是最后一个条目的可选键(当多个条目具有相同的 orderBy 条件值时)。因此,要正确对引用进行分页,您需要传递上一个条目的 createdAt它的键。

const baseQuery = dbRef
  .orderByChild('createdAt')
  .limitToFirst(limit);

let pageCount = 0, lastChildOnPage = undefined;
const children = [];

while (true) {
  const pageQuery = pageCount === 0
    ? baseQuery
    : baseQuery
       .startAfter(lastChildOnPage.createdAt, lastChildOnPage.key);
 
  const pageSnapshot = await pageQuery.once('value');

  pageSnapshot.forEach((childSnapshot) => {
    children.push({ key: childSnapshot.key, ...childSnapshot.val() });
  })

  const newLastChildOnPage = children[children.length-1];

  if (lastChildOnPage !== newLastChildOnPage) {
    lastChildOnPage = newLastChildOnPage;
    pageCount++;
  } else {
    break; // no more data
  }
}

console.log(`Grabbed ${pageCount} page(s) of data, retrieving ${children.length} children`);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多