有没有一种方法可以获取使用 Firestore 批量创建的文档的自动生成 ID?
使用时.add()
我可以轻松获得 ID:
db.collection('posts')
.add({title: 'Hello World'})
.then(function(docRef) {
console.log('The auto-generated ID is', docRef.id)
postKey = docRef.id
});
Using .batch()
我可以添加一个文档.doc()
and .set()
:
const batch = db.batch();
const postsRef = db.collection('posts').doc(postKey);
batch.set(postsRef, {title: 'Hello Again, World'});
const votesRef = db.collection('posts').doc(postKey)
.collection('votes').doc();
batch.set(votesRef, {upvote: true})
batch.commit().then(function() {
});
我可以获得添加到的文档的自动生成的 IDvotes
?
Update:
道格·史蒂文森 (Doug Stevenson) 是正确的 - 我可以在以下位置访问 ID:votesRef.id
你打电话时doc() https://firebase.google.com/docs/reference/js/v8/firebase.firestore.CollectionReference#doc没有任何参数,它将立即返回文档参考 https://firebase.google.com/docs/reference/js/v8/firebase.firestore.DocumentReference具有唯一的 id,无需向数据库写入任何内容 - id 是在客户端生成的。因此,如果您想要该 id,只需使用该 DocumentReference 上的 id 属性即可。在您编写该文档后,该 ID 将在数据库中可见。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)