如何将 "reference" 值插入到 firestore 中?

How do you insert a "reference" value into firestore?

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


UI绝对可以做到:

字段的值必须是 DocumentReference 类型。看起来你在里面放了一些其他对象,它有一个名为 id 的 属性,它是一个字符串。

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

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

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

  firebase.firestore()
    .collection("applications")
    .doc(applicationId)
    .get()
    .then((application) => {
      application.data().property.get().then((property) => { ... })
    })

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

示例代码:

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

db.collection('posts').add(post)

这是要存储在 firestore 中的模型 class。

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" }
}

我需要存储具有参考值的 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);
  }

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

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

似乎最近的更新使上述答案现在已经过时了。有趣的是,现在解决方案更简单了。他们删除了 .ref 选项,但现在会自动获取 ref。

所以你可以这样做:

const member = this3.$Firestore.doc('users/' + user2.user.uid);
this3.$Firestore.collection('teams').doc(this3.teamName).set({
  name: this3.teamName,
  members: [member],
});

其中 member 是文档参考,就这么简单。 (忽略这个 哈哈。)