10
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

firestoreでcollectionGroupを使ってorderByしたい。

Last updated at Posted at 2020-09-03

collectionに対しては特に何もしなくてもindexが作成されているみたいなのでorderByが使える。
だけどcollectionGroupになるとindexは自動では作られないとの事

#collection
コレクションの取得


const db = firebase.firestore()

db.collection("images").orderBy("timeStamp", "desc").limit(5).get()

これはちゃんと降順に取得できる

#collectionGroup
コレクション内にあるサブコレクションの取得

####フィールド

  message: "テスト"
  displayName: "testUser"
  timeStamp: 2020年9月3日 14:10:46 UTC+9

db.collectionGroup("comment").orderBy("timeStamp", "desc").limit(10).get()

これを実行すると下記のエラーが出て取得できない

Uncaught (in promise) FirebaseError: The query requires a COLLECTION_GROUP_DESC index for collection comment and field timeStamp. You can create it here

__index__がないからできませんよ
といっているらしい
#設定
firebaseコンソール>firestore>インデックス>単一フィールド

collection group scopeと書いてあるところがすべて無効になっています。

除外を追加を選択

設定前.png

今回の場合だとcollectionGroup("comment")なのでコレクションIDcomment
フィールドのパスtimeStampを使いたいのでtimeStampと入力して
コレクショングループにチェックを入れてNext

設定2.png

昇順降順を使用したいので有効にして保存

設定3.png
除外のところに新しく設定したものが表示されます

設定4.png

これで先ほどと同じ

db.collectionGroup("comment").orderBy("timeStamp", "desc").limit(10).get()

を実行してみます。

ちゃんと降順で取得することができました。

10
4
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
10
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?