如何在Firestore中插入“参考”值?

Ask*_*ous 12 javascript firebase angularfire2 google-cloud-firestore

我正在尝试将文档插入集合中。我希望文档具有reference要插入到集合中的类型的属性。但是每次我插入到集合中时,它都会以字符串或对象的形式出现。如何以编程方式插入reference类型化的值?

在此处输入图片说明


绝对有可能在用户界面中做到这一点:

在此处输入图片说明

tro*_*jek 22

可能最简单的解决方案是将引用键的值设置为doc(collection/doc_key)

示例代码:

post = {
        conetnet: "content...",
        title: "impresive title",
        user: db.doc('users/' + user_key),
    };

db.collection('posts').add(doc)
Run Code Online (Sandbox Code Playgroud)

  • 很棒的提示。我不明白这个答案,直到我意识到 Firestore 可以识别该引用并自动应用它。我原以为这个建议是说复制数据,我错了! (4认同)

Phi*_*eng 11

我今天试图解决这个问题,我找到的解决方案是使用.doc()来创建文档参考

  firebase.firestore()
    .collection("applications")
    .add({
      property: firebase.firestore().doc(`/properties/${propertyId}`),
      ...
    })
Run Code Online (Sandbox Code Playgroud)

这将在字段上存储DocumentReference类型,property因此在读取数据时,您将能够像这样访问文档

  firebase.firestore()
    .collection("applications")
    .doc(applicationId)
    .get()
    .then((application) => {
      application.data().property.get().then((property) => { ... })
    })
Run Code Online (Sandbox Code Playgroud)


uza*_*y95 5

这是存储在 firestore 中的模型类。

import { AngularFirestore, DocumentReference } from '@angular/fire/firestore';

export class FlightLeg {
  date: string;
  type: string;

  fromRef: DocumentReference; // AYT Airport object's KEY in Firestore
  toRef: DocumentReference;   // IST  {key:"IST", name:"Istanbul Ataturk Airport" }
}
Run Code Online (Sandbox Code Playgroud)

我需要存储具有参考值的 FlightLeg 对象。为此:

export class FlightRequestComponent {

  constructor(private srvc:FlightReqService, private db: AngularFirestore) { }

  addFlightLeg() {
    const flightLeg = {
      date: this.flightDate.toLocaleString(),
      type: this.flightRevenue,
      fromRef: this.db.doc('/IATACodeList/' + this.flightFrom).ref,
      toRef: this.db.doc('/IATACodeList/' + this.flightTo).ref,
    } as FlightLeg
    .
    ..
    this.srvc.saveRequest(flightLeg);
  }
Run Code Online (Sandbox Code Playgroud)

该服务可以将引用另一个对象的对象保存到firestore中:

export class FlightReqService {
   .
   ..
   ...
  saveRequest(request: FlightRequest) {
    this.db.collection(this.collRequest)
           .add(req).then(ref => {
              console.log("Saved object: ", ref)
           })
   .
   ..
   ...
  }
}
Run Code Online (Sandbox Code Playgroud)