문서 ID에 대한 Firestore 데이터베이스 쿼리
파이어스토어 데이터베이스에 문서 ID를 쿼리하려고 합니다.현재 다음 코드를 가지고 있습니다.
db.collection('books').where('id', '==', 'fK3ddutEpD2qQqRMXNW5').get()
결과가 안 나와요.그러나 다른 필드를 쿼리하면 작동합니다.
db.collection('books').where('genre', '==', 'biography').get()
문서 ID의 이름을 어떻게 부르나요?
조금 늦었지만, 사실 이것을 할 수 있는 방법이 있습니다.
db.collection('books').where(firebase.firestore.FieldPath.documentId(), '==', 'fK3ddutEpD2qQqRMXNW5').get()
이 기능은 방화벽 보안 규칙을 처리할 때 액세스가 허용된 레코드만 쿼리하려는 경우에 유용할 수 있습니다.
사용해 보십시오.
db.collection('books').doc('fK3ddutEpD2qQqRMXNW5').get()
(첫 번째 쿼리는 'id'라는 명시적인 사용자 설정 필드를 찾는 것입니다. 이 필드는 아마도 사용자가 원하는 필드가 아닐 것입니다.)
사용할 수 있습니다.__name__
쿼리에서 문서 ID를 사용하는 키워드입니다.
이것 대신에db.collection('books').doc('fK3ddutEpD2qQqRMXNW5').get()
당신은 쓸 수 있습니다.
db.collection('books').where('__name__', '==' ,'fK3ddutEpD2qQqRMXNW5').get()
.
이 경우 당신은 길이 배열을 얻어야 합니다.1
뒤로.
파이어베이스 문서에는 규칙 설명서에 이 기능이 나와 있습니다.https://firebase.google.com/docs/reference/rules/rules.firestore.Resource
2021년 6월
새로운 v9 모듈식 sdk는 트리 쉐이킹이 가능하며 컴파일된 앱이 더 작습니다.모든 새로운 Firestore 앱에 권장됩니다.
import { doc, getDoc } from "firebase/firestore";
const snap = await getDoc(doc(db, 'books', 'fK3ddutEpD2qQqRMXNW5'))
if (snap.exists()) {
console.log(snap.data())
}
else {
console.log("No such document")
}
이것은 소방서 문서의 예를 기반으로 합니다.
import { doc, getDoc } from "firebase/firestore";
const docRef = doc(db, "cities", "SF");
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("Document data:", docSnap.data());
}
else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
당신은 이것을 도우미 기능으로 만들 수 있습니다.
async function getDocument (coll, id) {
const snap = await getDoc(doc(db, coll, id))
if (snap.exists())
return snap.data()
else
return Promise.reject(Error(`No such document: ${coll}.${id}`))
}
getDocument("books", "fK3ddutEpD2qQqRMXNW5")
모든 사람들이 사용하라고 하는 동안.get()
전적으로 합리적이지만 항상 그런 것은 아닙니다.
다음을 기준으로 데이터를 필터링할 수 있습니다.id
(a 사용)where
예를 들어 쿼리).
Firebase v9 모듈식 SDK에서는 다음과 같이 작업할 수 있습니다.
import {collection, documentId} from 'firebase/firestore'
const booksRef = collection('books')
const q = query(booksRef, where(documentId(), '==', 'fK3ddutEpD2qQqRMXNW5'))
당신은 그것으로 문서를 얻을 수 있습니다.id
다음 패턴을 따릅니다.
firebase
.firestore()
.collection("Your collection")
.doc("documentId")
.get()
.then((docRef) => { console.log(docRef.data()) })
.catch((error) => { })
현재 클라우드 기능은 다음과 같은 방식으로 사용해야 할 경우에만 사용됩니다.
// Import firebase-admin
import * as admin from "firebase-admin";
// Use FieldPath.documentId()
admin.firestore.FieldPath.documentId()
const targetUser = await db.collection("users").where(admin.firestore.FieldPath.documentId() "==", "givenId").get();
지정된 문서 ID를 가진 문서는 하나뿐이므로 경로를 통해 ID 값을 직접 사용하는 것이 더 간단합니다.
const targetUser = await db.doc("users/"+ "givenId").get();
그러나 다음과 같이 지정된 ID 배열을 Firebase 컬렉션에 일치시키는 경우에는 실제로 사용해야 할 수도 있습니다.
const admin = require("firebase-admin");
const arr = ["id1", "id2"];
const refArr = arr.map(id => admin.firestore().collection("media").doc(id));
const m = await admin
.firestore()
.collection("media")
.where(admin.firestore.FieldPath.documentId(), "in", refArr)
.get();
이 마지막 예는 이 토론에서 나온 것입니다.
도우미 기능이 있는 동적 쿼리를 더 많이 찾는다면 이를 시도하면 됩니다.
import { db} from '@lib/firebase';
import {query, collection, getDocs ,documentId } from "firebase/firestore";
const getResult = async (_value) => {
const _docId = documentId()
const _query = [{
field: _docID,
operator: '==',
value: _value
}]
// calling function
const result = await getDocumentsByQuery("collectionName", qColl)
console.log("job result: ", result)
}
// can accept multiple query args
const getDocumentsByQuery = async (collectionName, queries) => {
const queryArgs = [];
queries.forEach(q => {
queryArgs.push(
where(q.field, q.operator, q.value)
);
});
const _query = query(collection(db, collectionName), ...queryArgs);
const querySn = await getDocs(_query);
const documents = [];
querySn.forEach(doc => {
documents.push({ id: doc.id, ...doc.data() });
});
return documents[0];
};
var docRef = db.collection("cities").doc("SF");
docRef.get().then(function(doc) {
if (doc.exists) {
console.log("Document data:", doc.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
이 링크는 제가 Golang SDK에서 해결을 찾고 있을 때 처음 나온 링크이므로, 다른 사람이 찾을 경우를 대비하여 제 솔루션을 추가하겠습니다.
package main
import (
"context"
"fmt"
"log"
"cloud.google.com/go/firestore"
firebase "firebase.google.com/go/v4"
"google.golang.org/api/option"
)
type (
Car struct {
ID string
Name string `firestore:"name"`
Make string `firestore:"make"`
Price float64 `firestore:"make"`
}
)
func main() {
ctx := context.Background()
// Use a service account
options := option.WithCredentialsFile("PATH/TO/SERVICE/FILE.json")
// Set project id
conf := &firebase.Config{ProjectID: "PROJECT_NAME"}
// Initialize app
app, err := firebase.NewApp(ctx, conf, options)
if err != nil {
log.Fatal(err)
}
// Get firestore client
client, err := app.Firestore(ctx)
if err != nil {
log.Fatal(err)
}
defer client.Close()
collectionRef := client.Collection("CAR_COLLECTION")
// firestore.DocumentID == "__name__"
docSnap, err := collectionRef.Where(firestore.DocumentID, "==", collectionRef.Doc("001")).Get(ctx)
if err != nil {
log.Fatal(err)
}
// Unmarshall item
car := Car{}
docSnap.DataTo(&car)
car.ID = docSnap.Ref.ID
// Print car list
fmt.Println(car)
}
여기서 혼란을 해소하기 위해서입니다.
기억하세요, 당신은 사용해야 합니다.async/await
여부에 대한 데이터 가져오기collection
한 개의 단하나면아니.doc
.
async function someFunction(){
await db.collection('books').doc('fK3ddutEpD2qQqRMXNW5').get();
}
언급URL : https://stackoverflow.com/questions/47876754/query-firestore-database-for-document-id
'programing' 카테고리의 다른 글
ngModel을 사용하여 양식 컨트롤을 상위 formGroup 디렉티브에 등록할 수 없습니다. (0) | 2023.06.05 |
---|---|
화면 하단에서 보기를 정렬하려면 어떻게 해야 합니까? (0) | 2023.06.05 |
Android에서 ListView 사이의 줄을 제거하려면 어떻게 해야 합니까? (0) | 2023.06.05 |
패키지에서 setup.py (setuptools)에 정의된 버전을 가져오려면 어떻게 해야 합니까? (0) | 2023.06.05 |
UITableViewController가 없는 UIRefreshControl (0) | 2023.06.05 |