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

时间:2017-10-15 07:28:03

标签: 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
});

使用.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?

更新

道格史蒂文森是正确的 - 我可以在votesRef.id

访问该ID

3 个答案:

答案 0 :(得分:14)

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

答案 1 :(得分:3)

我有类似的问题,而且我在firestore的API上发生了变化。

我收到的错误代码如下:

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

我发现必要的更改是获取doc对象的ref

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

我希望这能帮到你们所有人!

答案 2 :(得分:0)

为了在创建文档之前自动生成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);