programing

Firestore에서 'reference' 유형의 필드로 쿼리 중

closeapi 2023. 6. 10. 09:07
반응형

Firestore에서 'reference' 유형의 필드로 쿼리 중

ID가 5gF5FqRPvdroRF8isOwd인 단일 문서를 포함하는 'categories'라는 컬렉션이 있습니다.

저는 '티켓'이라는 다른 컬렉션을 가지고 있습니다.각 티켓에는 특정 범주에 티켓을 할당하는 참조 필드가 있습니다.

티켓 컬렉션의 필드는 '카테고리'라고 하며 필드 유형은 다음과 같습니다.reference.

아래 코드에서,categoryDocId쿼리할 범주의 문서 ID입니다.

const categoryDocID = `5gF5FqRPvdroRF8isOwd`;

const files = await firebase
  .firestore()
  .collection('tickets')
  .where('category', '==', categoryDocID)
  .get();

왜 그럴까요?files.length0을 반환합니까?

테스트를 위해, 저는 그것을 바꿨습니다.category필드 유형을 문자열로 지정하고 직접 참조 대신 범주 ID로 설정합니다.이것은 범주에 할당된 티켓을 올바르게 반환했으며, 이는 내가 어떻게 쿼리하는지에 대한 것이라고 믿게 합니다.reference들판.

여기 문서에서 읽으실 것처럼 참조 데이터 유형은 문서 참조를 저장하는 데 사용됩니다.

쿼리에 사용하려면 문서의 UID(즉, UID)도 아닌 단순 문자열을 사용할 수 없습니다.'5gF5FqRPvdroRF8isOwd') 또는 필드에 저장된 문자열 값(예:'/categories/5gF5FqRPvdroRF8isOwd').

다음과 같이 Document Reference를 작성하여 쿼리에 사용해야 합니다.

JS SDK V9

import { doc, query, collection, where, getDocs } from "firebase/firestore";

const categoryDocRef = doc(db, "categories", "5gF5FqRPvdroRF8isOwd");

const q = query(
  collection(db, "tickets"),
  where("category", "==", categoryDocRef)
);

const files = await getDocs(q);   // !! files is a QuerySnapshot

JS SDK V8

const categoryDocRef = firebase.firestore()
   .collection('categories')
   .doc('5gF5FqRPvdroRF8isOwd');

const files = await firebase   // !! files is a QuerySnapshot
  .firestore()
  .collection('tickets')
  .where('category', '==', categoryDocRef)
  .get();

Firebase Version 9(2021년 12월 업데이트)

"categories/5gF5FqRPvdroRF8isOwdand"를 사용하여 문서 참조를 작성한 다음 쿼리에 사용해야 합니다.

import { doc, query, collection, where, getDocs } from "firebase/firestore";

const categoryDocRef = doc(db, "5gF5FqRPvdroRF8isOwd");

const q = query(
  collection(db, "tickets"),
  where("category", "==", categoryDocRef)
);

const ticketDocsSnap = await getDocs(q);

참조 유형을 사용하여 컬렉션(node.js + typescript)을 쿼리하는 방법은 다음과 같습니다.

let myCollectionADocument = await admin.firestore().collection("collection_a").doc("documentId").get();
let myCollectionB = await admin.firestore().collection("collection_b").where("collection_a_id", "==", myCollectionADocument.ref).get();

언급URL : https://stackoverflow.com/questions/53140913/querying-by-a-field-with-type-reference-in-firestore

반응형