自动为文档生成ID,而不是在Firestore中生成ID

Urc*_*boy 1 android firebase google-cloud-firestore

我已经阅读了Firestore文档,但还没有找到一个示例,其中有类似的内容。

collection
       |--document
                |--{auto-generated-id}
                                  |--property1:value1
                                  |--property2:value2
                                  |--peoperty3:value3
Run Code Online (Sandbox Code Playgroud)

我经常看到的是:

collection     
         |--{auto-generated-id}
                            |--property1:value1
                            |--property2:value2
                            |--peoperty3:value3
Run Code Online (Sandbox Code Playgroud)

在前者中,我无法add()在文档上调用-(生成唯一ID)。但是,这可以在集合中完成,如上一个草图所示。

因此,我的问题是:在创建文档后,firestore有什么方法可以帮助自动生成id,即如何实现以下目标:

db.collection("collection_name").document("document_name").add(object)
Run Code Online (Sandbox Code Playgroud)

pie*_*etz 9

现在 firebase javascript API v9 已经发布,语法发生了一些变化。

import { collection, addDoc } from "firebase/firestore"; 

// Add a new document with a generated id.
const docRef = await addDoc(collection(db, "cities"), {
  name: "Tokyo",
  country: "Japan"
});
console.log("Document written with ID: ", docRef.id);
Run Code Online (Sandbox Code Playgroud)

您可以将其包装在 try/catch 块中来处理错误。

总之:

  • 如果您想自动生成 ID,请使用addDoc()+collection()
  • 如果你想设置ID使用setDoc()+doc()


Ale*_*amo 8

如果使用的是CollectionReference的add()方法,则意味着:

将具有指定POJO作为内容的新文档添加到此集合中,并自动为其分配一个文档ID。

如果要获取生成的文档ID并在引用中使用它,请使用DocumentReference的set()方法:

覆盖此DocumentRefere引用的文档

就像下面的代码行:

String id = db.collection("collection_name").document().getId();
db.collection("collection_name").document(id).set(object);
Run Code Online (Sandbox Code Playgroud)


Bal*_*len 5

这个答案可能有点晚,但您可以在此处查看此代码,它将生成一个新的文档名称:

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

让 Cloud Firestore 为您自动生成 ID 会更方便。你可以通过调用来做到这一点add()

将数据添加到 Cloud Firestore上阅读更多相关信息