11
10

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 5 years have passed since last update.

FirestoreのSubCollectionの簡単な使い方(最低限メモ)

Last updated at Posted at 2019-12-21

記事化するようなことでもありませんが、ま、メモということで。
SubCollectionにするか、別に分けたコレクションを作るかはいつも悩みます。

下記で試していることは3つ。

  • サブコレクションの作成(コレクションとサブコレクションを新規に同時で作るような状況)
  • コレクション取得時にサブコレクションがどう見えるか(見えない確認)
  • GroupCollectionを利用した検索

いろいろな書き方はあるかと思うが一旦下記のようにした。

ECサイトとかで一人のユーザーが「一般ユーザー」、「ショップ運営者」、「管理者」とかの権限を持つような状況を想定(したが、あまりいいサンプルではない。別Collectionを用意したほうがいいかも)。

const admin = require('firebase-admin');

admin.initializeApp({
    credential: admin.credential.cert('/path/to/key.json'),
    databaseURL: 'https://xxxxxxxxxx.firebase.com',
});

const db = admin.firestore();

(async () => {

    //サブコレクション作成
    const docId = db.collection("users").doc().id;
    await db.collection("users").doc(docId).set({ name: 'hoge' });
    await db.collection("users").doc(docId).collection("shopInfo").doc(docId).set({ level: 'user', id:docId });
    await db.collection("users").doc(docId).collection("adminInfo").doc(docId).set({ level: 'admin', id:docId });

    //サブコレクション参照
    const snapshots = await db.collection("users").doc(docId).collection("shopInfo").get();
    snapshots.docs.map(doc => {
        console.log(doc.data());
    })

    //CollectionGroup
    const groupSnapshots = await db.collectionGroup("shopInfo").where('level','==','user').get();
    groupSnapshots.docs.map(doc => {
        console.log(doc.data());
    })

})()

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?