【Firebase Functions】指定したドキュメントのフィールドの値を取得する

Firebase Functionsのindex.js内で、指定したドキュメント内の値にアクセスしたい場合があります。

具体的には以下の枠線で囲まれた部分をどのように取得するのか、という話です。
f:id:nekorokkekun:20191101101145p:plain

以下のコードを例にとってみてみましょう。

exports.addFanpageMember =
functions.firestore
.document("fanPages/{fanpageId}")
.onCreate(async (snap, context) => {
  const val = snap.data();
  try {
  await admin
  .firestore()
  .collection("fanPages")
  .doc(context.params.fanpageId)
  .collection("members")
  .doc(val.userId)
  .set({ permission: "pageOwner" });
  return;
} catch (error) {
  console.log(error);
  await snap.ref.set({ error: userFacingMessage(error) }, { merge: true });
  console.error(error);
  console.log(`user: ${context.params.userId}`);
}
});


重要なのは以下の部分です。

functions.firestore
.document("fanPages/{fanpageId}")
.onCreate(async (snap, context) => {
  const val = snap.data();

snapには現時点でのfanPages/{fanpageId}で指定したドキュメント内のデータが入っています。そこで、そのデータを取り出すために「const val = snap.data();」という形で記述しています。

このように書くことで、以下のようにオブジェクト形式でデータが入ります。

{ artistName: 'FunctionsTestファンページの紹介',
body: 'FunctionsTestファンページの紹介',
category: 'singer',
monthlyFee: '12456',
pageName: 'FunctionsTestファンページの紹介',
userId: 'aE91BXgT8fZaDiikdTRF4dmRzhF2' }

.doc(val.userId)のように書いてあげればuserIdが取得できます。その他も同様に取得できます。