Can I get the generated ID for a document created with batch().set using Firestore?

前端 未结 3 1899
囚心锁ツ
囚心锁ツ 2021-02-18 23:09

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

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

相关标签:
3条回答
  • 2021-02-18 23:34

    In order to generate the uid automatically beforehand the creation of document, you can make use of createID() function from angularFireAuth as follows:

    `

    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);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-18 23:37

    I had similar issue, And I thing there were changes at the API of firestore.

    I was getting an error for code like :

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

    The change I found that was necessary is to take the ref of the doc object:

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

    I hope this helps you all !

    0 讨论(0)
提交回复
热议问题