Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting UID Reference for Firestore

I'm trying to get a reference to a document's UID so I can use the document elsewhere in my project by it's UID. As per the documentation, I'm doing the following with AngularFire2 (v5):

var ref= this.afs.collection(placeToAdd).doc();

This gives me the following error: "Expected 1 arguments but got 0". It wants me to put an argument in the doc() method. So instead, I do:

var ref= this.afs.collection(placeToAdd).doc(thing);

then I set my Firebase object:

ref.set({
        item1: 'value 1',
        item2: 'value 2',
        item3: 'value 3'
      });

How do I get the ref's Firestore-generated UID now?

like image 837
FiringBlanks Avatar asked Jan 29 '23 07:01

FiringBlanks


2 Answers

Figured it out:

let newUID = this.afs.createId();

Then create this firestore object at the location of newUID:

var ref= this.afs.collection(placeToAdd).doc(thing);
like image 68
FiringBlanks Avatar answered Jan 31 '23 21:01

FiringBlanks


To clarify: there is two ways of inserting data in firestore. One recieves the uid from you.

db.collection(collection).doc(uid).set(data);

The other is adding the thocument but letting firestore generate the uid for you.

db.collection(collection).add(documentData)
.then(ref => {
    console.log("Document written with ID: ", ref.id);
});

It's important to note that both set and add return a promise of document ref, in case you want to use it and for error handling.

The documentation covers this in much more detail.

like image 40
Thiago Coutinho Avatar answered Jan 31 '23 22:01

Thiago Coutinho