LoginSignup
21
15

More than 3 years have passed since last update.

コピペで使うFirebase【Firestore ページング編】

Last updated at Posted at 2019-12-02

公式ドキュメント

クエリカーソルを使用したデータのページ設定

概要

ページングのメモ

Firestoreを使用してページング実装する場合は、クエリーカーソルを使う。
orderByメソッドで指定されたフィールドで始まる新しいクエリを作成して返す。

メソッド一覧
メソッド 動作
startAt クエリの開始点(クエリーカーソルを含む)からのデータを返す
startAfter クエリの開始点(クエリーカーソルを含まない)からのデータを返す
endAt クエリの終着点(クエリーカーソルを含む)からのデータを返す
endBefore クエリの終着点(クエリーカーソルを含まない)からのデータを返す

サンプル

firestoreのコレクションは以下としいidを昇順で並べる

コレクション名: member
ドキュメント
{ id: 1, name: "taro" }
{ id: 2, name: "hana" }
{ id: 3, name: "aki" }
{ id: 4, name: "yuto" }
{ id: 5, name: "ryo" }

startAt

startAt
firebase
    .firestore()
    .collection('member')
    .orderBy('id', 'asc')
    .startAt(3)
    .get()
    .then(querySnapshot => {
        let memberList = []; 
        querySnapshot.forEach(doc => memberList.push(doc.data()));
        console.log(memberList);
        // [{ id: 3, name: "aki" }, { id: 4, name: "yuto" }, { id: 5, name: "ryo" }]
    })

startAfter

startAfter
firebase
    .firestore()
    .collection('mamber')
    .orderBy('id', 'asc')
    .startAfter(3)
    .get()
    .then(querySnapshot => {
        let memberList = []; 
        querySnapshot.forEach(doc => memberList.push(doc.data()));
        console.log(memberList);
        // [{ id: 4, name: "yuto" }, { id: 5, name: "ryo" }]
    })

endAt

endAt
firebase
    .firestore()
    .collection('mamber')
    .orderBy('id', 'asc')
    .endAt(3)
    .get()
    .then(querySnapshot => {
        let memberList = []; 
        querySnapshot.forEach(doc => memberList.push(doc.data()));
        console.log(memberList);
        // [{ id: 1, name: "taro" }, { id: 2, name: "hana" }, { id: 3, name: "aki" }]
    })

endBefore

endBefore
firebase
    .firestore()
    .collection('mamber')
    .orderBy('id', 'asc')
    .endBefore(3)
    .get()
    .then(querySnapshot => {
        let memberList = []; 
        querySnapshot.forEach(doc => memberList.push(doc.data()));
        console.log(memberList);
        // [{ id: 1, name: "taro" }, { id: 2, name: "hana" }, { id: 3, name: "aki" }]
    })

ドキュメント スナップショットを使用したサンプル

※ うまく動かない... ドキュメント見てる感じだと動くはず

firebase
    .firestore()
    .collection('member')
    .where('name', "==",'hana')
    .get()
    .then(documentSnapshot => {
        const cursor = documentSnapshot.docs[0].data();
        firebase
            .firestore()
            .collection('member')
            .orderBy('id', 'asc')
            .startAt(cursor)
            .get()
            .then(snapshot => {
                snapshot.forEach(doc => {
                console.log("doc", doc.data());
            })
        })
    });
21
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
15