9

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

8 Answers 8

11

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);
  }
5
  • 1
    Thanks, simplest answer on here.
    – Capo
    Commented Oct 16, 2018 at 19:31
  • 1
    What class "this.firestore" represets? Collection? Can't find this on documentation Commented Mar 14, 2019 at 18:37
  • constructor(private firestore: AngularFirestore) { } Commented Mar 15, 2019 at 21:59
  • 1
    Assuming I create e.g. thousands of documents in one process, will this (possibly) lead to duplicate IDs? (assuming that createId() does not "reserve" the ID for some time) Commented Feb 19, 2021 at 17:37
  • In short, auto-generate iDs are statistically unique with a good enough probability to consider it all the time. Commented Feb 22, 2021 at 14:15
6

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().

12
  • But if I used AutoId.newId() I'm going to save a different id? Not sure if I'm following you... I was thinking to create a new id, something like this: const newSetID = '_' + Math.random().toString(36).substr(2, 9); It would be different but well... I can work with that one. It's just a reference at the end
    – Dani
    Commented Jan 16, 2018 at 15:30
  • I'm not sure if you could also make this generated id the default one
    – Dani
    Commented Jan 16, 2018 at 15:31
  • Your code is similar to AutoId.newId(), except that the latter is much less likely to generate a duplicate ID. There is no such thing as a "default id" in Firestore: whatever you specify to document(myNewId) is the ID of the document. If you don't specify anything there, or call add() the Firestore SDK generates an ID for you with the code I linked. Commented Jan 16, 2018 at 15:50
  • I can't use a different one anyway... When I do const newSet: AngularFirestoreDocument<SetModel> = this.AngularFirestore.doc('users/' + this.navParams.data.userId + '/' + this.navParams.data.set.id); I need to point to the "real" one. The one as a reference on the collection, not as a property of my document anyway
    – Dani
    Commented Jan 16, 2018 at 15:51
  • How can I generate this AutoId.newId()? I tried with my NewSet but it doesn't have any AutoId property/method
    – Dani
    Commented Jan 16, 2018 at 15:53
2

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
})
2

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 } });
})
0

I was getting my documents with this:

this.itemsCollection.valueChanges()

I changed it to:

this.sets = this.itemsCollection.snapshotChanges()

Now I can get they id with $key and update my document without extra references.

More info:

https://github.com/angular/angularfire2/issues/1278

How to get firebase id

Edit: this is the solution I needed but not exactly for what I was looking for here

0

I think the this would be a good solution if your intention is to know the record's id when querying the collection.

firebase.firestore().collection('sets').get()
    .then(querySnapshot => {
      querySnapshot.forEach(doc => {
        this.sets.push({ ...doc.data(), id: doc.id })
      })
    })
    .catch(error => {
      console.log(error)
    })
0

This is how i ended up doing this. I create a document and then add the data after receiving the promise.

firebase.firestore.collection('instances').doc("WDXmpzpY1TWRIJjeBNrx")
.collection("suppliers").add({}).then(docRef 
=> {
    firebase.firestore.collection('instances').doc("WDXmpzpY1TWRIJjeBNrx")
    .collection("suppliers").doc(docRef.id).set({
       name:this.supplierForm.name,
       phone:this.supplierForm.phone,
       email:this.supplierForm.email,
       address:this.supplierForm.address,
       gstNo:this.supplierForm.gstNo,
       uniqueID: docRef.id,
    })
 }).catch(err => {console.log(err)})
0

This show how you can set your own ID in a document, replace MY_ID to your own ID then use the SET command to store the object into the document. this function return void, so you cant check or get any callback.

db.collection("persons").doc("MY_ID").set({
    name: "JOHN",
})

this example show how to store in the person collection a obj. with name JOHN.

1
  • While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. From Review Commented Mar 31, 2020 at 9:51

Not the answer you're looking for? Browse other questions tagged or ask your own question.