Firestore - 如何在将文档添加到集合后获取文档ID

时间:2018-02-12 06:07:19

标签: firebase firebase-realtime-database google-cloud-firestore

有没有办法获取将文档添加到集合后生成的文档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)

6 个答案:

答案 0 :(得分:12)

是的,这是可能的。在集合上调用.add方法时,将返回DocumentReference对象。 DocumentReference具有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。访问documentation了解其他语言。

答案 1 :(得分:8)

我建议使用粗箭头功能,因为即使在.then函数中,它也可以使用this.foo

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))

使用函数(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)
})

虽然粗箭头功能将允许您按预期访问this.foo

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

答案 2 :(得分:2)

如果要使用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 => { ... })

或者您可以让调用函数捕获错误。

答案 3 :(得分:1)

对于Android和Java,假设您在set()或add()到Firestore之前获取文档ID。像这样:

//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()); 

答案 4 :(得分:0)

正如其他人所提到的,添加文档后,我们可以获得文档参考。 代表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');
    }
  }

答案 5 :(得分:-1)

正如您所提问题,这就是我的工作。不确定这是否是最佳做法,但可以轻松访问。

首先创建文档

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 })