如何在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
相关产品推荐
相关产品推荐

