6
3

More than 3 years have passed since last update.

FirestoreでMapオブジェクト内のフィールドに対してWhere検索する

Last updated at Posted at 2021-06-21

はじめに

以下のような、Mapオブジェクトを持つコレクションに対してWhere句で条件指定してデータ取得するメモ。
自分用備忘録を兼ねる。(むしろそっちの目的が大きい)
image.png
image.png

検索方法

where('[フィールド名].[Mapオブジェクト内のフィールド名]' , '==' , 'hogehoge')のように指定する。
上の例だとwhere('data.name','==','hogehoge')とする。
以下Node.jsのサンプル

const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
const hogehoge = db.collection('Hogehoge');

async function getHogehoge() {
    try {
        const querySnapShot = await hogehoge.where('data.name' , '==' , 'hogehoge').get(); // ここで条件指定する
        var datas = [];

        querySnapShot.forEach(async (d)=>{
            datas.push(await d.data());
        });

        return datas;

    } catch(err) {
        throw err;
    }
}
module.exports = {
    getHogehoge: getHogehoge,
};

演算子==の部分は公式ドキュメントに載っている他の演算子も利用可能。
https://firebase.google.com/docs/firestore/query-data/queries?hl=ja#query_operators
上記のドキュメントにはMapオブジェクトに対するWhereの指定が明記されてないように見えたので一応自分用にメモとして興した。

FieldPathを使う方法

where('data.name')のように、whereメソッド内のフィールド名部分にドットを書いて直接記述しても動作するのだが、FiledPathを使うやり方もある。

const { firestore } = require('firebase-admin');

...

const querySnapShot = await hogehoge.where(new firestore.FieldPath('data' , 'name') , '==' , 'hogehoge');

new firestore.FieldPath('data' , 'name')where('data.name')と同じ働きをする。
公式ドキュメントはこちら↓
https://firebase.google.com/docs/reference/js/firebase.firestore.FieldPath?hl=ja

6
3
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
6
3