我正在尝试在firestore中实现文档引用。我创建了两个集合:Customers
和Purchased-Property
。每次在Purchased-Property
集合中创建新文档时,我如何引用Purchased-Property_Customer_id
中的Customer_id
。代码如下所示:
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
})
CustomerDoc
是DocumentReference对象。每个DocumentReference都有一个id
属性。你可以这样简单地使用它:
PurchasedPropertyDoc.set({
Purchased_Property_id: PurchasedPropertyDoc.id,
Purchased_Property_Name: Property_Name,
Purchased_Property_Location: Property_Location,
Purchased_Property_Customer_Id: CustomerDoc.id
})
这与您在第一个文档中首次使用CustomerDoc.id
的方式没有什么不同。如果在创建文档时没有此引用,则无法建立关联。
您必须创建一个ref,如:
const CustomerRef = db.collection( "users" ).doc( userId )
然后设置为Purchased_Property_Customer_Id:CustomerRef