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

Bre*_*uro 14 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)
Run Code Online (Sandbox Code Playgroud)

小智 21

对的,这是可能的.在.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);
});
Run Code Online (Sandbox Code Playgroud)

这个例子是用JavaScript编写的.访问其他语言的文档.


Bre*_*rne 13

如果你想使用async/await而不是.then(),你可以这样写:

const post = async (doc) => {
    const doc_ref = await db.collection(my_collection).add(doc)
    return doc_ref.id
}
Run Code Online (Sandbox Code Playgroud)

如果要捕获此函数中的任何错误,请包括.catch()

    const doc_ref = await db.collection(my_collection).add(doc).catch(err => { ... })
Run Code Online (Sandbox Code Playgroud)

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


小智 9

我建议使用胖箭头功能,因为它打开了即使在.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))
Run Code Online (Sandbox Code Playgroud)

使用函数(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)
})
Run Code Online (Sandbox Code Playgroud)

胖箭头函数允许您按预期访问this.foo

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


Ant*_*ber 6

使用v9,您甚至可以在创建文档之前获取ID

  • 获取一个新的 docRef 并读取其随机数id
  • id根据需要使用
  • 例如,id在文档数据中插入
  • 然后创建文档
const usersRef = collection(db,'users') // collectionRef
const userRef = doc(usersRef) // docRef
const id = userRef.id // a docRef has an id property
const userData = {id, ...} // insert the id among the data
await setDoc(userRef, userData) // create the document
Run Code Online (Sandbox Code Playgroud)