我可以使用 Firestore 获取使用 batch().set 创建的文档的生成 ID 吗?

Can I get the generated ID for a document created with batch().set using 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
});

使用 .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() {
});

我可以获取添加到 votes 的文档的自动生成 ID 吗?

更新:

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

访问 ID

当您调用具有唯一 ID 的 doc() without any arguments, it will immediately return a DocumentReference 时,无需向数据库写入任何内容 - 该 ID 是在客户端生成的。因此,如果您想要该 ID,只需在该 DocumentReference 上使用 ID 属性。在您编写该文档后,该 ID 将在数据库中可见。

我遇到了类似的问题,我认为 firestore 的 API 发生了变化。

我收到如下代码的错误:

const postsRef = db.collection('posts').doc(postKey);
batch.set(postsRef, {title: 'Hello Again, World'});

我发现必要的更改是采用文档对象的 ref

const postsRef = db.collection('posts').doc(postKey).ref;

希望对大家有所帮助!

为了在创建文档之前自动生成 uid,您可以使用 angularFireAuth 中的 createID() 函数,如下所示:

`

constructor(
    private angularFireStore: AngularFirestore,
   ) {}

 const batch = this.angularFireStore.firestore.batch();

 const autogenUid = this.angularFireStore.createId();
 const collectionReference = this.angularFireStore.collection
                            ('collection_name').doc(autogenUid).ref;

 const docData = {first_field:'value', second_field:'value2'};
 batch.set(collectionReference, docData);