5
3

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 1 year has passed since last update.

【FirebaseSDK(v9)】FirestoreでドキュメントIDを複数指定して取得する方法

Posted at

以下コレクションが存在する場合に各取得方法の簡単な例(JavaScript or TypeScript)

accounts
L XXXXXXXX
  L name = xさん
  L frendIds = [YYYYYYYY, ZZZZZZZZ]
L YYYYYYYY
  L name = yさん
  L frendIds = [XXXXXXXX]
L ZZZZZZZZ
  L name = zさん
  L frendIds = [XXXXXXXX]

ドキュメントIDを1つ指定して、ドキュメントを1つ取得する場合

import { initializeApp } from 'firebase/app';
import { doc, getDoc, getFirestore } from 'firebase/firestore';

const app = initializeApp();
const db = getFirestore(app);

const snapshot = await getDoc(doc(db, 'accounts', 'XXXXXXXX');
snapshot.exists() && console.log(snapshot.id);
// XXXXXXXX

フィールドを指定して、複数ドキュメントを取得する場合

import { initializeApp } from 'firebase/app';
import { collection, getDocs, query, where } from 'firebase/firestore';

const app = initializeApp();
const db = getFirestore(app);

const q = query(collection(db, 'accounts'), where('frendIds', 'array-contains', 'XXXXXXXX'));
const snapshot = await getDocs(q);
snapshot.forEach((doc) => {
  console.log(doc.id);
}
// YYYYYYYY, ZZZZZZZZ

ドキュメントIDを複数指定して、ドキュメントを複数取得したい場合

import { initializeApp } from 'firebase/app';
import { collection, documentId, getDocs, query, where } from 'firebase/firestore';

const app = initializeApp();
const db = getFirestore(app);

const q = query(collection(db, 'accounts', where(documentId(), 'in', [YYYYYYYY, ZZZZZZZZ]));
const snapshot = await getDocs(q);
snapshot.forEach((doc) => {
  console.log(doc.id);
}
//  YYYYYYYY, ZZZZZZZZ

不明点等ある方はコメントやSNSでDMいただけるとお答えいたします🙋‍♂️
楽しい開発ライフを!

5
3
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?