Firestore - 在添加之前是否可以获取ID?

Tal*_*rda 44 firebase google-cloud-firestore

我知道在Realtime Databasepush ID之前我可以得到它像这样:

 DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference();
        String challengeId=databaseReference.push().getKey();
Run Code Online (Sandbox Code Playgroud)

然后我可以使用此ID添加它.

我也能把它拿到 Cloud Firestore?

34m*_*4m0 84

这在文档中有所涉及.请参阅添加文档部分的最后一段.

DocumentReference ref = db.collection("my_collection").document();
String myId = ref.getId();
Run Code Online (Sandbox Code Playgroud)

  • 通过`this.db.collection('collections')使用angularFire2让它工作.ref.doc().id` (6认同)
  • 我已更新此答案以替换旧的 api。 (2认同)

Alb*_*ino 25

const db = firebase.firestore();
const ref = db.collection('your_collection_name').doc();
const id = ref.id;
Run Code Online (Sandbox Code Playgroud)

  • 请说明您的答案,而不仅仅是转储代码 (6认同)
  • @SterlingArcher 有什么需要解释的吗?诚实的问题。 (6认同)
  • @Ruan,我很久以前被告知的一个典型考虑是“如果不需要解释,那就是一个问题”。在此基础上,我们假设自从我们回答问题以来,通常需要解释“为什么”来帮助学习 (3认同)

Jon*_*han 23

火力地堡 9

doc(collection(this.afs, 'posts')).id;
Run Code Online (Sandbox Code Playgroud)


Jas*_*ssi 14

projectsRef是firestore集合ref.

data是您要上传到firestore的具有键值的对象.

afs是在构造函数中注入的angularfirestore模块

您可以通过以下方式执行此操作(代码适用于AngularFire2 v5,类似于任何其他版本的firebase SDK,例如web,节点等)

const pushkey = this.afs.createId();
const project = {' pushKey': pushkey, ...data };
this.projectsRef.doc(pushkey).set(project);
Run Code Online (Sandbox Code Playgroud)

这将在Collection上生成一个名为projectsRef的新文档,其id为pushKey,该文档的pushKey属性与文档的id相同

请记住,set也会删除任何现有数据

实际上.add()和.doc().set()与.add()相同,id是自动生成的,使用.doc().set()可以提供自定义id.


tom*_*ozb 6

对于 Node.js 运行时

const documentRef = admin.firestore()
  .collection("pets")
  .doc()

await admin.firestore()
  .collection("pets")
  .doc(documentRef.id)
  .set({ id: documentRef.id })
Run Code Online (Sandbox Code Playgroud)

这将创建一个具有随机 ID 的新文档,然后将文档内容设置为

{ id: new_document_id }
Run Code Online (Sandbox Code Playgroud)

希望能很好地解释这是如何工作的


Cod*_*ity 5

IDK 如果这有帮助,但我想从 Firestore 数据库中获取文档的 ID - 即已经输入到控制台的数据。

我想要一种简单的方法来即时访问该 ID,所以我只是将它添加到文档对象中,如下所示:

const querySnapshot = await db.collection("catalog").get();
      querySnapshot.forEach(category => {
        const categoryData = category.data();
        categoryData.id = category.id;
Run Code Online (Sandbox Code Playgroud)

现在,我可以id像访问任何其他属性一样访问它。

IDK 为什么id首先不只是一部分.data()


Fre*_*sar 5

最简单且更新的 (2019) 方法是主要问题的正确答案:

“是否可以在添加之前获取ID?”

// Generate "locally" a new document in a collection
const document = yourFirestoreDb.collection('collectionName').doc();

// Get the new document Id
const documentUuid = document.id;

// Sets the new document (object that you want to insert) with its uuid as property
const response = await document.set({
      ...yourObjectToInsert,
      uuid: documentUuid
});
Run Code Online (Sandbox Code Playgroud)