[英]How to assign document id to a variable in firestore?
I have created a firestore collection and am able to add data(documents) to it, and firestore automatically generates its document id. 我已经创建了一个Firestore集合,并且能够向其中添加数据(文档),并且Firestore会自动生成其文档ID。
Adding data 新增资料
this.afs.collection('questions').add({ 'question': message, 'asker': this.currentStudent, 'upvotes': this.upvote, 'lesson': this.currentLesson });
I would like to get the document id of this newly added document and assign it to a variable, something like: 我想获取这个新添加的文档的文档ID,并将其分配给变量,例如:
this.documentId = newlyGeneratedDocumentsId
I read somewhere that I can do this using the document.Set() method, if so, how may I go about doing this? 我读到某个地方可以使用document.Set()方法执行此操作,如果可以的话,我该怎么做?
The add()
methods returns a promise. add()
方法返回一个Promise。 When that promise resolves, it gives you the DocumentReference
of the new document. 该承诺解决后,它将为您提供新文档的DocumentReference
。
So you can get it with: 因此,您可以通过以下方式获得它:
this.afs.collection('questions')
.add({ 'question': message, 'asker': this.currentStudent, 'upvotes': this.upvote, 'lesson': this.currentLesson })
.then(function(documentRef) {
documentId = documentRef.id;
});
Also see my answer here: Firebase: Get document snapshot after creating 也可以在这里查看我的答案: Firebase:创建后获取文档快照
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.