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

Firebase Firestore-如何在将文档添加到集合后获取文档id,firebase,google-cloud-firestore,Firebase,Google Cloud Firestore,是否有方法获取将文档添加到集合后生成的文档id 如果我将文档添加到表示社交媒体应用程序中“帖子”的集合中,我希望获取该文档id并将其用作其他集合中另一个文档的字段 如果我无法获取添加文档后生成的文档Id,我是否应该计算一个随机字符串,并在创建文档时提供Id?这样我就可以使用与我的其他文档中的字段相同的字符串了 快速结构示例: POST (collection) Document Id - randomly generated by firebase or by me USER (coll

是否有方法获取将文档添加到集合后生成的文档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对象。DocumentReference具有
id
字段,因此您可以在创建文档后获取id

//使用生成的id添加新文档。
db.集合(“城市”)。添加({
名称:“东京”,
国家:“日本”
})
.then(功能(docRef){
console.log(“使用ID编写的文档:”,docRef.ID);
})
.catch(函数(错误){
console.error(“添加文档时出错:”,错误);
});

这个例子是用JavaScript编写的。请访问以了解其他语言。

如果使用Promissions,我建议使用fat arrow函数,因为它甚至可以在
函数中使用
this.foo

db.collection(“城市”)。添加({
名称:“东京”,
国家:“日本”
})
。然后(docRef=>{
console.log(“使用ID编写的文档:”,docRef.ID);
log(“您现在也可以访问this.as-expected:”,this.foo)
})
.catch(error=>console.error(“添加文档时出错:”,错误))
使用
函数(docRef)
意味着您无法访问
this.foo
,将抛出错误

.then(函数(docRef){
console.log(“使用ID编写的文档:”,docRef.ID);
log(“您现在无法访问this.as-expected:”,this.foo)
})
而胖箭头函数将允许您按预期访问
this.foo

。然后(docRef=>{
console.log(“使用ID编写的文档:”,docRef.ID);
log(“您现在也可以访问this.as-expected:”,this.foo)
})

编辑/添加2020:

现在更流行的方法可能是使用async/await。请注意,您必须在函数声明前面添加
async

异步函数addCity(newCity){ const newCityAdded=wait db.collection(“cities”).add(newCity) log(“新城市:”,newCityAdded) log(“它的id:”,newCityAdded.id) }
如果你只想要这个id,可以使用描述来抓取它。分解结构允许您获取响应中的任何键/值对:

异步函数addCity(newCity){ const{id}=await db.collection(“cities”).add(newCity) log(“新城市的id:”,id) } 也可以使用destructuring获取值并重命名为您想要的任何值:

异步函数addCity(newCity){ const{id:newCityId}=wait db.collection(“cities”).add(newCity) log(“新城市的id:”,newCityId) }
如果要使用
async/await
而不是
。然后()
,可以这样编写:

const post = async (doc) => {
    const doc_ref = await db.collection(my_collection).add(doc)
    return doc_ref.id
}
如果要捕获此函数中的任何错误,请包括
.catch()


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

下面是我所做的,正如您在问题中提到的。不确定这是否是最佳实践,但它很容易访问

首先创建文档时

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

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

对于Android、Java,您应该在
set()
add()
到Firestore之前获取文档ID。像这样:

//字段:
CollectionReference toolsCollectionRef=FirebaseFirestore.getInstance().collection(toolsCollection);
自定义POJO_模型工具选项;
//在方法上:
字符串newDocID=toolsCollectionRef.document().getId()//首先获取文档ID。
toolToPost.setToolID(newDocID);
//现在使用文档ID:
toolsCollectionRef.document(newDocID).set(toolToPost.getConvertedTool_KeyValuePair()).addOnCompleteListener(new OnCompleteListener()){
@凌驾
未完成的公共void(@NonNull任务){
}
});
//在其他帖子中重复使用相同ID:
usersCollectionRef.document(mAuth.getUid()).collection(usersToolsCollection).document(toolToPost.getToolID()).set(toolToPost.getConvertedTool_KeyValuePair());

检查此项。您可以在添加文档之前生成密钥。这对您来说太难处理了。您可能会生成一个已经存在的ID,这将损坏您的数据。谢谢!这很有帮助。我能够获取文档ID。然后,我想获取该ID,将用户发送到一个新的URL,该URL动态生成,ID构成URL的一部分,并显示来自firebase firestore的该特定文档的数据。欢迎任何想法/帮助。您可以为此使用模板文字:
window.location.href=`https://mypage.com/${id}`
。请注意,url周围不是
,而是使使用此方法成为可能的反勾号。另一种方法是使用id创建一个新字符串,类似于此:
const newUrl=”https://mypage.com“+id
,然后
window.location.href=newUrl
。如果您以前没有使用过模板文本,请检查它(),使用它很好:)
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');
    }
  }