我可以使用firestore获取使用batch()创建的文档的生成ID吗? [英] Can I get the generated ID for a document created with batch().set using Firestore?

查看:74
本文介绍了我可以使用firestore获取使用batch()创建的文档的生成ID吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法可以获取使用Firestore作为批处理的一部分创建的文档的自动生成ID?

Is there a way that I can get the auto-generated ID for a document created as part of a batch using Firestore?

使用 .add()我可以很容易地获得一个ID:

When using .add() I can easily get an ID:

db.collection('posts')
  .add({title: 'Hello World'})
  .then(function(docRef) {
    console.log('The auto-generated ID is', docRef.id)
    postKey = docRef.id
});

使用 .batch()我可以添加包含 .doc() .set()的文档:

Using .batch() I can add a document with .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() {
});

我是否可以获得添加到的文档的自动生成ID投票

Can I get the auto-generated ID of the document that was added to votes?

更新:

Doug Stevenson是正确的 - 我可以在 votingRef.id

Doug Stevenson is correct - I can access the ID at votesRef.id

推荐答案

访问ID当您在没有任何参数的情况下致电 doc()时,将立即返回具有唯一ID的 DocumentReference ,无需撰写数据库的任何内容 - 在客户端上生成id。因此,如果您想要该id,只需在该DocumentReference上使用id属性即可。在您编写该文档后,该ID将在数据库中可见。

When you call doc() without any arguments, it will immediately return a DocumentReference that has a unique id, without writing anything to the database - the id is generated on the client. So if you want that id, simply use the id property on that DocumentReference. That id will become visible in the database after you've written that document.

这篇关于我可以使用firestore获取使用batch()创建的文档的生成ID吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆