Save ID to Firestore document

12,018

Solution 1

From quickly scanning the reference documentation for CollectionReference.add(...) I see that add(...) returns a promise. It seems there is no way to get the auto-generated ID before the document is created.

But keep in mind that the document IDs are just client-side keys that are statistically guaranteed to be unique.

This code shows what the JavaScript SDK does to generate the ID, which just boils down to calling AutoId.newId(). You can also call (or include in case it isn't publicly exported) this in your own code, and then use doc(myId) instead of add().

Solution 2

1 - create a const id. 2 - set id in object. 3 - save

  createEvent(set){
    const id = this.firestore.createId();
    set.id = id;
    return this.firestore.doc(`users/${id}`).set(ev);
  }

Solution 3

if this is still the a question, here is what I found, you need to create an empty doc and get the id and then set the document content. in your case it would be something like this.

const newDoc = newSet.collection('sets').doc()
const newDocRef = await newDoc.get()

and now set the whole document:

await newSet.collection('sets').doc(newDocRef.id).set({
    docId: newDocRef.id,
    // res of the document
})

Solution 4

Here other options.

In Firebase:

saveAlert(alert: Alert) {
    const alertsCollection = this.firestore.collection<Alert>('alerts');
    const id = this.firestore.createId();
    alert.code = id;
    return alertsCollection.doc(id).set(alert);
}

In NodeJS:

app.post('/', async (req, res) => {
    const data = {
        code: '',
        name: req.body.name,
        description: req.body.description
    }
    const reference = db.collection('alerts').doc();
    data.code = reference.id;
    await reference.set(data);
    res.json({ status: 'success', data: { alert: data } });
})
Share:
12,018
Dani
Author by

Dani

for (1 &lt; 2) { eat(); code(); for (true === true) { beer(); } sleep(); }

Updated on July 29, 2022

Comments

  • Dani
    Dani almost 2 years

    I'd like to save the id of my document as a property as well, not only as a reference on the collection. At the moment I save it like this:

    const newSet: AngularFirestoreDocument<SetModel> = this.AngularFirestore.doc('users/' + this.navParams.data.userId);
    
        // adding user to our ddbb
        newSet.collection('sets').add(this.set)
          .then(function (docRef) {
            // ok
          })
          .catch(function (error) {
            // error
          });
    

    Would be that possible? Or do I need to save it, get the id and update it again?

    PS this is my ddbb structure: enter image description here

    enter image description here