utu*_*rnr 13 javascript firebase google-cloud-firestore
有没有办法可以使用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
});
Run Code Online (Sandbox Code Playgroud)
使用.batch()我可以使用.doc()和添加文档.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() {
});
Run Code Online (Sandbox Code Playgroud)
我可以获取添加到的文档的自动生成的ID votes吗?
更新:
Doug Stevenson是正确的 - 我可以访问ID votesRef.id
Dou*_*son 18
当你调用没有任何参数的doc()时,它将立即返回一个具有唯一id 的DocumentReference,而不向数据库写任何内容 - 在客户端上生成id.因此,如果您想要该id,只需在该DocumentReference上使用id属性即可.在您编写该文档后,该ID将在数据库中可见.