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?
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With