Firebase RTDB limitToLast(n, orderByKey(ref)) causes TypeError: Cannot read properties of undefined (reading 'pieceNum_')

Firebase RTDB limitToLast(n, orderByKey(ref)) causes TypeError: Cannot read properties of undefined (reading 'pieceNum_')

我正在使用 Firebase v9.0.2

错误:

Uncaught TypeError: Cannot read properties of undefined (reading 'pieceNum_')

<-- 4361

--> https://www.gstatic.com/firebasejs/9.0.2/firebase-database.js

代码变量:

CHAT_ROOT/chats/${chatroomid}chatroomid 的值取自之前的用户输入。

代码:

import { Database } from 'initAppGlobals.js';
import * as FirebaseDB from 'https://www.gstatic.com/firebasejs/9.0.2/firebase-database.js';

// this code contains nesting of unction calls
FirebaseDB.onValue(
  FirebaseDB.limitToLast(1,
    FirebaseDB.orderByKey(
      FirebaseDB.ref(Database, CHAT_ROOT)
    )
  ),
(snapshot) => {
  // Load messages into UI as HTML
}, (error) => {
  // display error message
});

可能的问题

以上代码仅在我同时删除 limitToLastorderByKey 函数时才有效。

所以,这有效:

import { Database } from 'initAppGlobals.js';
import * as FirebaseDB from 'https://www.gstatic.com/firebasejs/9.0.2/firebase-database.js';

// this code contains nesting of function calls
FirebaseDB.onValue(
  FirebaseDB.ref(Database, CHAT_ROOT),
(snapshot) => {
  // Load messages into UI as HTML
}, (error) => {
  // display error message
});

但这会随着数据库大小的增长而影响性能。

数据库规则:

{
  "chats": {
    "$chatroomid": {
      ".read": "auth !== null",
      ".write": "auth !== null",
      ".indexOn": ".value"
    }
  }
}

您将调用嵌套得太远,并且没有根据条件创建查询。

要创建一个查询,您需要一个引用,然后是一些查询操作,所以:

const query = FirebaseDB.query(
  FirebaseDB.ref(Database, CHAT_ROOT),
  FirebaseDB.limitToLast(1),
  FirebaseDB.orderByKey()
);

然后你可以执行查询:

FirebaseDB.onValue(query, (snapshot) => {
  // Load messages into UI as HTML
}, (error) => {
  // display error message
});