2

let say I have a collection named Countries and a doc looks like below

{
  name: "Pakistan"
  //other field removed to focus on problem only
}

and a Collection names Cities which doc have above country field reference looks like

{
  name: "Karachi",
  //other field removed to focus on problem only
  city: "3FbRFiWB4DmfdcxDdei3" //reference of country document
}

now I am displaying the countries and cities as ordered drop down menus as user select country then the next drop down displays filtered cities

let countryRef = this.angularFireStore.collection('Countries', ref => ref);
let countries = countryRef.valueChanges();

and html binding looks like

let country of country | async"

Here is the actual problem on any change or select event of user I have to pass id of country to populated filtered cities based of selected country but I can't got id in country. How to achieve this any help will be greatly appreciated.

NOTE: I know I can got id and other metadata by getting snapshot change but that response very late I just want id field in reference binding for editing or updating Documents.

Abdul Hameed
  • 1,008
  • 1
  • 15
  • 35
  • use `.snapshotChanges()` instead of `countryRef.valueChanges();`. check this [answer](https://stackoverflow.com/questions/47221248/how-to-retrieve-the-id-of-a-single-firestore-document/47223346#47223346). Another option would be save the id with the country doc while creating it. – Hareesh Feb 26 '18 at 10:40
  • @Hareesh thanks one more thing, how can I update query ref dynamically when country field selected. i.e `this.angularFireStore.collection('Cities', ref => ref.where('country', '==', 'selectedcountryID'));` – Abdul Hameed Feb 26 '18 at 10:57
  • @Hareesh `.snapshotChanges()` is very slow other wise I will go with it, didn't you read my `Note` section – Abdul Hameed Feb 26 '18 at 11:02
  • you can use select options change event ` – Hareesh Feb 26 '18 at 11:14

1 Answers1

3

As you said you don't want to use .snapshotChanges() and get id with .valueChanges() you need to store it while creating the doc. Do this in your add country function

this.tempId = this.angularFireStore.createId();

const newCountry = {
      id:this.tempId,
      name:'Karachi'
      //other fields...
    }

this.angularFireStore.collection('Countries').doc(this.tempId).set(newCountry).then(res => {
  console.log('country added')
}).catch(err => {
  console.log('error adding country',err)
});
Hareesh
  • 6,770
  • 4
  • 33
  • 60