问题
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:
回答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().
回答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);
}
回答3:
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
回答4:
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)
})
回答5:
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
})
来源:https://stackoverflow.com/questions/48284184/save-id-to-firestore-document