Firestore - 如何在将文档添加到集合后获取文档 ID [英] Firestore - How to get document id after adding a document to a collection
问题描述
有没有办法获取将文档添加到集合后生成的文档ID?
Is there a way to acquire the document id that was generated after adding a document to a collection?
如果我将一个文档添加到代表社交媒体应用中帖子"的集合中,我想获取该文档 ID 并将其用作不同集合中另一个文档中的字段.
If I add a document to a collection that represents a "post" in a social media app, I want to get that document id and use it as a field in another document in a different collection.
如果我无法获取添加文档后生成的文档 ID,是否应该只计算一个随机字符串并在创建文档时提供该 ID?这样我就可以使用与其他文档中的字段相同的字符串?
If I can't get the document Id that was generated after adding a document, should I just compute a random string and supply the id when creating the document instead? That way I can use that same string as the field in my other document?
快速结构示例:
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.
Yes it is possible. When you call the .add
method on a collection, a DocumentReference object is returned. DocumentReference has the id
field, so you can get the id after the document was created.
// 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 example is in JavaScript. Visit the documentation for other languages.
这篇关于Firestore - 如何在将文档添加到集合后获取文档 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!