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}
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.
what make thing even confusing is, the result includes m:0
!!
however if I go with startAfter(0)
, the result is {b: 6, d: 5, p: 1, y: 4}
which is expected.
how exactly does the 2nd argument work?
2
Answers
Ok, I think I understand how it works
first we order according to the orderBy clause, in this case we order by value
to understand what
startAfter(0,'b')
return, we simply imagine whereb:0
would be locatedsince
b
come beforem
, so everything afterb:0
is what we will get, which is everythingwith the same logic, we can deduce what
endAt(6, 'd')
returnthe result would be also everything
the trick is to know where the reference point is
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. It is only applied after the filter on the regular value has been executed.When we order your data by value, we get:
Since there’s only one node with value
0
, the database returns all nodes after that one.