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

2023-12-25

有没有办法获取将文档添加到集合后生成的文档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 对象。文档参考有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 编写的。参观文档 https://firebase.google.com/docs/firestore/manage-data/add-data#add_a_document对于其他语言。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Firestore - 将文档添加到集合后如何获取文档 ID 的相关文章

随机推荐