skip to Main Content

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


  1. Chosen as BEST ANSWER

    Ok, I think I understand how it works

    first we order according to the orderBy clause, in this case we order by value

    { 
      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

    { 
      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

    with the same logic, we can deduce what endAt(6, 'd') return

    { 
      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


  2. 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:

    { 
      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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search