user23424
user23424

Reputation: 71

Reference type in firestore

I'm trying to implement documentreference in firestore. I created two collections : Customers and Purchased-Property. How can i reference the Customer_id in the Purchased-Property_Customer_id everytime a new document is created in the Purchased-Property collection. The code is shown below:

 const CustomerDoc = firebase.firestore().collection("Customers").doc()
CustomerDoc.set({
       Customer_id: CustomerDoc.id,
       Customer_Name: Name
       Customer_PhoneNumber: PhoneNumber

    })

const PurchasedPropertyDoc = firebase.firestore().collection("Purchased-Property").doc()
    PurchasedPropertyDoc.set({
           Purchased_Property_id: PurchasedPropertyDoc.id,
           Purchased_Property_Name: Property_Name,
           Purchased_Property_Location: Property_Location,
           Purchased_Property_Customer_Id: Customer_Id   //How do i make  reference to this Customer_Id in the Customers collection everytime a new document under the Purchased-Property collection is made 


    
        })

Upvotes: 1

Views: 477

Answers (2)

You have to create a ref like:

const CustomerRef = db.collection( "users" ).doc( userId )

and then set as Purchased_Property_Customer_Id:CustomerRef

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317402

CustomerDoc is a DocumentReference object. Every DocumentReference has an id property. You can simply use it like this:

    PurchasedPropertyDoc.set({
           Purchased_Property_id: PurchasedPropertyDoc.id,
           Purchased_Property_Name: Property_Name,
           Purchased_Property_Location: Property_Location,
           Purchased_Property_Customer_Id: CustomerDoc.id
    })

It's no different than the way you first used CustomerDoc.id in your first document. If you don't have this reference available at the time you create the document, then you won't be able to make the association.

Upvotes: 2

Related Questions