menote nhanga
menote nhanga

Reputation: 115

Firestore Firebase create fielID equal Document ID

Can anyone tell me how to create a field Id that is equal to the Document ID. I have done like below however is very inconsistent sometimes the documentID is equal field ID other times not. I want them to always be the save.

  void saveOrders() async {
    await _db.collection(_collectionOrders).add(
        {
          "id": _db.collection(_collectionOrders).document().documentID,
        }
        ).then((value){
    });
  }

thanks in advance.

Upvotes: 0

Views: 52

Answers (1)

Matthias
Matthias

Reputation: 4163

You could do this in two steps:

  1. Create your document without the id:

    DocumentReference doc = await _db.collection(_collectionOrders).add({'your': 'data'});

  2. Update the newly created document and add the id property:

    await doc.update({'id': doc.id});

You can now be sure that you inserted the right documentId.

Upvotes: 1

Related Questions