【发布时间】:2018-12-19 21:38:56
【问题描述】:
我正在尝试将文档插入到集合中。我希望文档具有 reference 类型的属性以插入到集合中。但是每次我插入到集合中时,它都会以字符串或对象的形式出现。如何以编程方式插入 reference 类型的值?
在 UI 中绝对可以做到:
【问题讨论】:
标签: javascript firebase google-cloud-firestore angularfire2
我正在尝试将文档插入到集合中。我希望文档具有 reference 类型的属性以插入到集合中。但是每次我插入到集合中时,它都会以字符串或对象的形式出现。如何以编程方式插入 reference 类型的值?
在 UI 中绝对可以做到:
【问题讨论】:
标签: javascript firebase google-cloud-firestore angularfire2
可能最简单的解决方案是将引用键的值设置为doc(collection/doc_key),因为需要DocumentReference。
示例代码:
post = {
content: "content...",
title: "impressive title",
user: db.doc('users/' + user_key),
};
db.collection('posts').add(post)
【讨论】:
db.doc('users/' + user_key).ref 中删除.ref 后才有效,因为db.doc() 本身返回一个DocumentReference。
我今天试图解决这个问题,我得到的解决方案是使用.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) => { ... })
})
【讨论】:
ERROR FirebaseError: Function addDoc() called with invalid data,如果我只是设置它存储的字符串,这意味着这个对象/代码行会导致这个错误。我尝试添加 .ref 将其转换为 DocumentReference,但现在它似乎根本没有执行。
这是要存储在 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" }
}
我需要使用参考值存储 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)
})
.
..
...
}
}
【讨论】:
字段的值必须是DocumentReference 类型。看起来您要在其中放置一些其他对象,该对象具有名为 id 的属性,这是一个字符串。
【讨论】:
reference 类型的字段执行where 查询。那可能吗?如果它很复杂,我可以提出另一个 stackoverflow 问题。
似乎最近的更新使上述答案现在已过时。有趣的是,现在解决方案变得更加容易。他们删除了 .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 是文档引用,就这么简单。 (忽略this3 lol。)
【讨论】: