programing

Firestore - 컬렉션에 문서를 추가한 후 문서 ID를 가져오는 방법

minimums 2023. 6. 12. 21:15
반응형

Firestore - 컬렉션에 문서를 추가한 후 문서 ID를 가져오는 방법

컬렉션에 문서를 추가한 후 생성된 문서 ID를 획득할 수 있는 방법이 있습니까?

소셜 미디어 앱에서 "게시물"을 나타내는 문서를 컬렉션에 추가하는 경우 해당 문서 ID를 가져와 다른 컬렉션의 다른 문서의 필드로 사용합니다.

문서를 추가한 후 생성된 문서 Id를 얻을 수 없다면, 문서를 생성할 때 임의의 문자열을 계산하여 id를 제공하면 됩니까?그러면 다른 문서의 필드와 동일한 문자열을 사용할 수 있습니까?

빠른 구조 예:

POST (collection)
    Document Id - randomly generated by firebase or by me
USER (collection)
    Document Id - randomly generated by firebase
       userPost: String (this will be the document id 
                         in the post collection that I'm trying to get)

네, 가능합니다.전화를 걸 때.add메서드가 컬렉션에 있으면 DocumentReference 개체가 반환됩니다.Document Reference에는 다음이 있습니다.id문서가 작성된 후 ID를 얻을 수 있는 필드입니다.

// Add a new document with a generated id.
db.collection("cities").add({
    name: "Tokyo",
    country: "Japan"
})
.then(function(docRef) {
    console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
    console.error("Error adding document: ", error);
});

이 예제는 JavaScript에 있습니다.다른 언어에 대해서는 설명서를 참조하십시오.

약속을 사용한다면 사용 가능성을 열어주기 때문에 지방 화살표 기능을 사용하는 것을 추천합니다.this.foo에도.then기능.

    db.collection("cities").add({
        name: "Tokyo",
        country: "Japan"
    })
    .then(docRef => {
        console.log("Document written with ID: ", docRef.id);
        console.log("You can now also access this. as expected: ", this.foo)
    })
    .catch(error => console.error("Error adding document: ", error))

사용.function(docRef)액세스할 수 없음을 의미합니다.this.foo그러면 오류가 발생할 것입니다.

    .then(function(docRef) {
        console.log("Document written with ID: ", docRef.id);
        console.log("You can now NOT access this. as expected: ", this.foo)
    })

Fat Arrow 기능을 통해 액세스할 수 있습니다.this.foo예상대로

    .then(docRef => {
        console.log("Document written with ID: ", docRef.id);
        console.log("You can now also access this. as expected: ", this.foo)
    })

2020년 편집/추가:

요즘 더 인기 있는 방법은 비동기/대기를 대신 사용하는 것일 수 있습니다.추가해야 합니다.async함수 선언 앞:

    async function addCity(newCity) {
      const newCityAdded = await db.collection("cities").add(newCity)
      console.log("the new city:", newCityAdded)
      console.log("it's id:", newCityAdded.id)
    }

그리고 만약 당신이 ID만 원한다면, 그것은 설명을 사용하여 잡을 수 있습니다.파괴를 통해 응답에서 모든 키/값 쌍을 가져올 수 있습니다.

    async function addCity(newCity) {
      const { id } = await db.collection("cities").add(newCity)
      console.log("the new city's id:", id)
    }

파괴를 사용하여 값을 파악하고 원하는 이름으로 바꿀 수도 있습니다.

    async function addCity(newCity) {
      const { id: newCityId } = await db.collection("cities").add(newCity)
      console.log("the new city's id:", newCityId)
    }

사용할 경우async/await대신에.then()다음과 같이 쓸 수 있습니다.

const post = async (doc) => {
    const doc_ref = await db.collection(my_collection).add(doc)
    return doc_ref.id
}

이 기능에서 오류를 발견하려면 다음을 포함합니다..catch():

    const doc_ref = await db.collection(my_collection).add(doc).catch(err => { ... })

또는 호출 함수가 오류를 감지하도록 할 수 있습니다.

Android, Java의 경우 문서 ID를 먼저 얻어야 합니다.set()또는add()파이어스토어로 보내주세요.이와 같은 경우:

    //Fields: 
    CollectionReference toolsCollectionRef = FirebaseFirestore.getInstance().collection(toolsCollection);
    CustomPOJO_Model toolToPost; 
    
    //In Methods: 
    String newDocID= toolsCollectionRef.document().getId();   //Get Doc ID first. 
    toolToPost.setToolID(newDocID);
    
    //Now use the doc ID:
    toolsCollectionRef.document(newDocID).set(toolToPost.getConvertedTool_KeyValuePair ()).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
        }
    });
    
    //Re-use same ID in another post: 
    usersCollectionRef.document(mAuth.getUid()).collection(usersToolsCollection).document(toolToPost.getToolID()).set(toolToPost.getConvertedTool_KeyValuePair()); 

v9를 사용하면 문서를 만들기 전에도 ID를 얻을 수 있습니다.

  • 새 docRef를 가져와서 임의로 읽습니다.id
  • 사용id당신이 원하듯이.
  • 예를 들어, 다음을 삽입합니다.id문서 데이터에서
  • 그런 다음 문서를 만듭니다.
const usersRef = collection(db,'users') // collectionRef
const userRef = doc(usersRef) // docRef
const id = userRef.id // a docRef has an id property
const userData = {id, ...} // insert the id among the data
await setDoc(userRef, userData) // create the document

FB Firestore 버전 9(JS/Web)의 경우 다음 구문을 사용합니다.

import { addDoc, doc, Timestamp, updateDoc } from "firebase/firestore";

    //add document to 'posts' collection with auto id
        const newItem = await addDoc(collection(db, 'posts'), {
                  caption: post.value.caption || "No caption provided",
                  location: post.value.location || "No location provided",
                  imageUrl: imageUrl.value,
                  createdAt: Timestamp.now(), 
            });
                
    //get new document id an update it to the file as id field.
    const fileID = newItem.id
                console.log('added file:', fileID);
                const updateDocId = doc(db, "posts", fileID) ;
                await updateDoc(updateDocId, {
                  id: fileID
              })

다른 사람들도 언급했듯이, 문서 참조가 추가되면 우리는 그것을 얻을 수 있습니다.ID를 대신하여 문서 참조를 받은 후 동일하게 업데이트할 수 있습니다.

Service.ts 파일

async funName(data: Data){
      let docRef = this.firestore.collection('table-name').add(data);
      console.log(docRef)
      try {
        const docAdded = await docRef;
        console.log(docAdded.id);
        this.firestore.doc('table-name/' + docAdded.id).update({ id: docAdded.id });
        return docRef;
      }
      catch (err) {
        return err;
      }
    }

component.ts 파일

async addData(){
    try{
      let res =  await this.dataServ.funName(this.form.value);
      this.snackbar.open('success', 'Success');
    }catch(ex){
      this.disabled = false;
      this.snackbar.open('err', 'Error')
      console.log(ex, 'exception');
    }
  }

파이어베이스 v9의 문서에 따르면, 당신이 사용하기를 원한다고 생각합니다.addDoc()방법: 예를 들어 다음과 같습니다.

import { collection, addDoc } from "firebase/firestore"; 

// Add a new document with a generated id.
const docRef = await addDoc(collection(db, "cities"), {
  name: "Tokyo",
  country: "Japan"
});
console.log("Document written with ID: ", docRef.id);

▁is도 있습니다.setDoc()에 할 수 있는 입니다.

import { doc, setDoc } from "firebase/firestore"; 

// Add a new document in collection "cities"
await setDoc(doc(db, "cities", "YOUR_CUSTOM_ID"), {
  name: "Los Angeles",
  state: "CA",
  country: "USA"
});

저는 왜 이것이 투표로 뽑혔는지 잘 모르겠습니다.이것이 제가 필요로 했던 것입니다. 저는 doc() 대신 doc().set()를 추가하기 위해 찾고 있었습니다.컬렉션 내부에서 사용자를 검색하기 위해 UUID를 문서로 사용할 것입니다.

firebase.firestore().collection("cities").doc().set({ name: Tokyo,
country: Japan })

질문에 언급된 바와 같이 제가 하는 일은 다음과 같습니다.베스트 프랙티스인지는 모르겠지만 쉽게 액세스할 수 있습니다.

처음에 문서를 작성할 때

firebase.firestore().collection("cities").doc().set({ name: Tokyo,
country: Japan })

문서의 ID를 설정하고 정확한 ID를 속성으로 넣을 수 있습니다.

firebase.firestore().collection("cities").doc('id-generated-from-somewhere')
.set({ id: 'id-generated-from-somewhere', name: Tokyo, country: Japan })

언급URL : https://stackoverflow.com/questions/48740430/firestore-how-to-get-document-id-after-adding-a-document-to-a-collection

반응형