[英]Firebase RTDB: How exactly the 2nd argument of cursors(startAt, endAt...) work?
code:代码:
import {
orderByValue,
ref,
getDatabase,
set,
get,
query,
startAfter
} from "firebase/database";
import { initializeApp } from "firebase/app";
const app = initializeApp({
projectId: "some-id"
});
const db = getDatabase();
const testRun = async () => {
await set(ref(db), { d: 5, y: 4, b: 6, m: 0, p: 1 });
const snapshot = await get(
query(ref(db), orderByValue(), startAfter(0, "b"))
);
console.log(snapshot.val());
};
testRun();
result: {b: 6, d: 5, m: 0, p: 1, y: 4}
结果:
{b: 6, d: 5, m: 0, p: 1, y: 4}
how is this make sense?这有什么意义? with
startAfter(0, 'b')
, I was expecting the result to be {d: 5, p: 1, y: 4}
, but that is not totally the case.使用
startAfter(0, 'b')
,我期望结果是{d: 5, p: 1, y: 4}
,但情况并非完全如此。
what make thing even confusing is, the result includes m:0
!!更令人困惑的是,结果包括
m:0
!
however if I go with startAfter(0)
, the result is {b: 6, d: 5, p: 1, y: 4}
which is expected.但是,如果我 go 与
startAfter(0)
,结果是{b: 6, d: 5, p: 1, y: 4}
这是预期的。
how exactly does the 2nd argument work?第二个论点究竟是如何工作的?
The second value you specify to startAfter
(and its sibling methods) is typically used as a so-called disambiguation key, in case there are multiple child nodes with the value that you pass in the first argument.您为
startAfter
指定的第二个值(及其同级方法)通常用作所谓的消歧键,以防有多个子节点具有您在第一个参数中传递的值。 It is only applied after the filter on the regular value has been executed.它仅在对常规值执行过滤器后应用。
When we order your data by value, we get:当我们按价值排序您的数据时,我们会得到:
{
m: 0,
p: 1,
y: 4,
d: 5,
b: 6
}
Since there's only one node with value 0
, the database returns all nodes after that one.由于只有一个节点的值为
0
,因此数据库会返回该节点之后的所有节点。
Ok, I think I understand how it works好的,我想我明白它是如何工作的
first we order according to the orderBy clause, in this case we order by value首先我们根据 orderBy 子句进行排序,在这种情况下我们按值排序
{
m: 0,
p: 1,
y: 4,
d: 5,
b: 6
}
to understand what startAfter(0,'b')
return, we simply imagine where b:0
would be located要了解
startAfter(0,'b')
返回的内容,我们只需想象b:0
的位置
{
b: 0, // imagine
m: 0,
p: 1,
y: 4,
d: 5,
b: 6
}
since b
come before m
, so everything after b:0
is what we will get, which is everything因为
b
在m
之前,所以b:0
之后的一切都是我们将得到的,这就是一切
with the same logic, we can deduce what endAt(6, 'd')
return用同样的逻辑,我们可以推导出
endAt(6, 'd')
返回什么
{
m: 0,
p: 1,
y: 4,
d: 5,
b: 6
d: 6, // imagine
}
the result would be also everything结果也是一切
the trick is to know where the reference point is诀窍是知道参考点在哪里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.