1

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 


    
        })

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

How then can i use the reference data type for easier location of the Customer_Id since the answer above, which is correct, store it as a string
Using a reference type isn't necessarily any easier. You still have to make a query for the other document. But you can just pass CustomerDoc directly if you want a reference.
0

You have to create a ref like:

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

and then set as Purchased_Property_Customer_Id:CustomerRef

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.