Firestore-将文档添加到集合后如何获取文档ID [英] Firestore - How to get document id after adding a document to a collection

查看:67
本文介绍了Firestore-将文档添加到集合后如何获取文档ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以获取将文档添加到集合后生成的文档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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆