You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Firestore中存储DocumentReference类型的引用数组?

解决Firestore存储DocumentReference数组的问题

你当前代码中this.store.doc(...)返回的是AngularFire封装的AngularFirestoreDocument对象,并非Firestore原生的DocumentReference实例,直接存储会被序列化为字符串。要存储真正的DocumentReference,需要获取原生引用对象,有两种可行方式:

方式一:通过AngularFirestoreDocument的ref属性获取原生引用

直接在doc()调用后追加.ref,拿到Firestore原生的DocumentReference:

constructor(private store: AngularFirestore) {}

this.store
  .collection('owners')
  .doc(this.owner.id)
  .update({
    trucks: [
      ...this.owner.trucks, // 确保这里的元素已经是原生DocumentReference
      this.store.doc(`/trucks/${documentReference.id}`).ref,
    ],
  });

方式二:直接用Firestore原生实例创建引用

通过this.store.firestore获取原生Firestore实例,再调用doc()创建DocumentReference:

constructor(private store: AngularFirestore) {}

// 先创建原生DocumentReference
const newTruckRef = this.store.firestore.doc(`/trucks/${documentReference.id}`);

this.store
  .collection('owners')
  .doc(this.owner.id)
  .update({
    trucks: [
      ...this.owner.trucks,
      newTruckRef,
    ],
  });

额外注意

如果this.owner.trucks之前存储的是字符串ID而非DocumentReference,需要先将其转换为原生引用再合并:

constructor(private store: AngularFirestore) {}

// 把字符串ID数组转为DocumentReference数组
const existingTruckRefs = this.owner.trucks.map(truckId => 
  this.store.firestore.doc(`/trucks/${truckId}`)
);

const newTruckRef = this.store.firestore.doc(`/trucks/${documentReference.id}`);

this.store
  .collection('owners')
  .doc(this.owner.id)
  .update({
    trucks: [...existingTruckRefs, newTruckRef],
  });

内容的提问来源于stack exchange,提问作者rgahan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 23:25:25