135

I know that in Realtime Database I could get the push ID before it was added like this:

 DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference();
 String challengeId=databaseReference.push().getKey();

and then I could add it using this ID.

Can I also get it in the Cloud Firestore?

1
  • Can we getting same in using Google Cloud Firestore REST API? Commented Jul 30, 2022 at 19:32

18 Answers 18

224
Answer recommended by Google Cloud Collective

This is covered in the documentation. See the last paragraph of the add a document section.

DocumentReference ref = db.collection("my_collection").doc();
String myId = ref.id;
Sign up to request clarification or add additional context in comments.

8 Comments

The same occurred to me... in firestore .document() does not give the impression of communicating with the database in the same was push() did. I believe the general view is that the likely hood of an id collision is so low that we do not have to be concerned with it.
@krv I don't see how .doc() would not work for you... 2 things you could verify are 1) you are using the correct method name for the sdk/library/language. .document() in java, .doc() in typescript/javascript. 2) you are calling .doc() on a collection reference and not a document reference. Bon courage!
got it working using angularFire2 by doing this.db.collection('collections').ref.doc().id
Thank you @krv! That was exactly what I needed to do. How did you find it? I find the documentation of angularFire too short, and the API of Firebase differs a little from AngularFire.
I've updated this answer with to replace the old apis.
|
52
const db = firebase.firestore();
const ref = db.collection('your_collection_name').doc();
const id = ref.id;

7 Comments

Please explain your answers, don't just dump out code
I'm using vue-fire and this one worked for me. Thanks.
@SterlingArcher What's there to explain? Honest question.
@Ruan a typical consideration that I was told a long time ago was “if it doesn’t need an explanation it would have been a question”. On that basis, we assume since were answering a question, an explanation as to why is usually required to help learn
@Ruan * How does this work * Does it only work for autogenerated keys * Does it work with transactions * Will I get a value before executing an update, or after * Is this answer up to date, or something changed. As a rule of thumb, please don't post snippets with no quoted source or explanation
|
26

You can do this in following manner (code is for AngularFire2 v5, which is similar to any other version of firebase SDK say web, node etc.)

const pushkey = this.afs.createId();
const project = {' pushKey': pushkey, ...data };
this.projectsRef.doc(pushkey).set(project);

projectsRef is firestore collection reference.

data is an object with key, value you want to upload to firestore.

afs is angularfirestore module injected in constructor.

This will generate a new document at Collection called projectsRef, with its id as pushKey and that document will have pushKey property same as id of document.

Remember, set will also delete any existing data

Actually .add() and .doc().set() are the same operations. But with .add() the id is auto generated and with .doc().set() you can provide custom id.

1 Comment

According to new angularFire update this is not working this.afs.createId();
23

Firebase 9

doc(collection(this.afs, 'posts')).id;

1 Comment

Perfect, I was about to post this exact question for firebase 9. Thank you.
22

The simplest and updated (2022) method that is the right answer to the main question:

"Is It Possible To Get The ID Before It Was Added?"

v8:

    // Generate "locally" a new document in a collection
    const document = yourFirestoreDb.collection('collectionName').doc();
    
    // Get the new document Id
    const documentUuid = document.id;
 
    // Sets the new document with its uuid as property
    const response = await document.set({
          uuid: documentUuid,
          ...
    });

v9:

    // Get the collection reference
    const collectionRef = collection(yourFirestoreDb,'collectionName');

    // Generate "locally" a new document for the given collection reference
    const docRef = doc(collectionRef); 

    // Get the new document Id
    const documentUuid = docRef.id;

    //  Sets the new document with its uuid as property
    await setDoc(docRef, { uuid: documentUuid, ... }) 

Comments

6

IDK if this helps, but I was wanting to get the id for the document from the Firestore database - that is, data that had already been entered into the console.

I wanted an easy way to access that ID on the fly, so I simply added it to the document object like so:

const querySnapshot = await db.collection("catalog").get();
      querySnapshot.forEach(category => {
        const categoryData = category.data();
        categoryData.id = category.id;

Now, I can access that id just like I would any other property.

IDK why the id isn't just part of .data() in the first place!

2 Comments

Wondering if it's a good practice to do so. It would definitely make sense besides easing the client side usage of the data models
Been a while since I looked at this, but I'm not aware of anything 'bad' from this approach.
6

For node.js runtime

const documentRef = admin.firestore()
  .collection("pets")
  .doc()

await admin.firestore()
  .collection("pets")
  .doc(documentRef.id)
  .set({ id: documentRef.id })

This will create a new document with random ID, then set the document content to

{ id: new_document_id }

Hope that explains well how this works

Comments

4

This is possible now (v9 2022 update) by generating Id locally:

import { doc, collection, getFirestore } from 'firebase/firestore'

const collectionObject = collection(getFirestore(),"collection_name") 
const docRef = doc(collectionObject)

console.log(docRef.id) // here you can get the document ID

Optional: After this you can create any document like this

setDoc(docRef, { ...docData })

Hope this helps someone. Cheers!

Comments

3

Unfortunately, this will not work:

let db = Firestore.firestore()

let documentID = db.collection(“myCollection”).addDocument(data: ["field": 0]).documentID

db.collection(“myOtherCollection”).document(documentID).setData(["field": 0])

It doesn't work because the second statement executes before documentID is finished getting the document's ID. So, you have to wait for documentID to finish loading before you set the next document:

let db = Firestore.firestore()

var documentRef: DocumentReference?

documentRef = db.collection(“myCollection”).addDocument(data: ["field": 0]) { error in
    guard error == nil, let documentID = documentRef?.documentID else { return }

    db.collection(“myOtherCollection”).document(documentID).setData(["field": 0])
}

It's not the prettiest, but it is the only way to do what you are asking. This code is in Swift 5.

Comments

2

docs for generated id

We can see in the docs for doc() method. They will generate new ID and just create new id base on it. Then set new data using set() method.

try 
{
    var generatedID = currentRef.doc();
    var map = {'id': generatedID.id, 'name': 'New Data'};
    currentRef.doc(generatedID.id).set(map);
}
catch(e) 
{
    print(e);
}

Comments

2

For the new Firebase 9 (January 2022). In my case I am developing a comments section:

const commentsReference = await collection(database, 'yourCollection');
await addDoc(commentsReference, {
  ...comment,
  id: doc(commentsReference).id,
  date: firebase.firestore.Timestamp.fromDate(new Date())
});

Wrapping the collection reference (commentsReference) with the doc() provides an identifier (id)

1 Comment

I think await in this line is redundant. const commentsReference = await collection(database, 'yourCollection');. collection() is a synchronous function. Rest of the things are 100% correct. Great explaination!
1

To get ID after save on Python:

doc_ref = db.collection('promotions').add(data)
return doc_ref[1].id

Comments

1

In dart you can use:

`var itemRef = Firestore.instance.collection("user")
 var doc = itemRef.document().documentID; // this is the id
 await itemRef.document(doc).setData(data).then((val){
   print("document Id ----------------------: $doc");
 });`

Comments

1

You can use a helper method to generate a Firestore-ish ID and than call collection("name").doc(myID).set(dataObj) instead of collection("name").add(dataObj). Firebase will automatically create the document if the ID does not exist.

Helper method:

/**
 * generates a string, e.g. used as document ID
 * @param {number} len length of random string, default with firebase is 20
 * @return {string} a strich such as tyCiv5FpxRexG9JX4wjP
 */
function getDocumentId (len = 20): string {
  const list = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
  let res = "";
  for (let i = 0; i < len; i++) {
    const rnd = Math.floor(Math.random() * list.length);
    res = res + list.charAt(rnd);
  }
  return res;
}

Usage: const myId = getDocumentId().

Comments

1

If you don't know what will be the collection at the time you need the id:

This is the code used by Firestore for generating ids:

const generateId = (): string => {
  // Alphanumeric characters
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let autoId = '';
  for (let i = 0; i < 20; i++) {
    autoId += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  // assert(autoId.length === 20, "Invalid auto ID: " + autoId);
  return autoId;
};

References:

Firestore: Are ids unique in the collection or globally?

https://github.com/firebase/firebase-js-sdk/blob/73a586c92afe3f39a844b2be86086fddb6877bb7/packages/firestore/src/util/misc.ts#L36

Comments

0

This works for me. I update the document while in the same transaction. I create the document and immediately update the document with the document Id.

        let db = Firestore.firestore().collection(“cities”)

        var ref: DocumentReference? = nil
        ref = db.addDocument(data: [
            “Name” : “Los Angeles”,
            “State: : “CA”
        ]) { err in
            if let err = err {
                print("Error adding document: \(err)")
            } else {
                print("Document added with ID: \(ref!.documentID)")
                db.document(ref!.documentID).updateData([
                    “myDocumentId” : "\(ref!.documentID)"
                ]) { err in
                    if let err = err {
                        print("Error updating document: \(err)")
                    } else {
                        print("Document successfully updated")
                    }
                }
            }
        }

Would be nice to find a cleaner way to do it but until then this works for me.

Comments

0

In Node

var id = db.collection("collection name").doc().id;

Comments

0

In Flutter:

DocumentReference docRef = yourRef.doc(); //get the premisse ref
final String yourNewDocId = docRef.id; //get the id
docRef.set({'your data' : 'here'}); //save the data on the id you just get

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.