angular - “AngularFirestoreDocument”类型上不存在属性“withConverter”
问题描述
我正在使用 ionic angular 和 firestore 构建一个网络应用程序。当我想获取文档的特定字段时,我知道我必须映射到一个对象,这就是我所做的。
export interface notificationModel{
notificationId?: string;
message?: string;
contactId?: string;
}
export class userModel{
userId?: string;
name?: string;
notifications?: notificationModel[];
contacts?: string[];
constructor (userId, name, notifications,contacts) {
this.name = name;
this.userId = userId;
this.notifications = notifications;
this.contacts = contacts;
}
getContacts(){
return this.contacts;
}
}
这里 userinfo 集合存储用户名、一个字符串数组的联系人列表和另一个称为通知类型通知的集合。
这是我的转换器
var userConverter = {
toFirestore: function(userModel) {
return {
userId: userModel.userId,
name: userModel.name,
notifications: userModel.notifications,
contacts: userModel.contacts,
}
},
fromFirestore: function(snapshot, options){
const data = snapshot.data(options);
return new userModel(data.userId, data.name, data.notifications,data.contacts)
}
我想获取用户并将其映射到我的用户模型/类,以便我可以自由使用数据,但似乎可以这样做。
这是我获取用户联系人但收到此错误的方法之一
“AngularFirestoreDocument”类型上不存在属性“withConverter”
this.userInfosCollection.doc(userId)
.withConverter(userConverter)
.get().then(function(doc) {
if (doc.exists){
// Convert to City object
var user = doc.data();
// Use a City instance method
console.log(user.getContacts());
} else {
console.log("No such document!")
}}).catch(function(error) {
console.log("Error getting document:", error)
});
}
除了解决这个错误,我想知道存储和检索这样的数据的最佳实践。谢谢!
解决方案
如本期所述,它在 AngularFire 官方存储库中打开,不幸的是withConverter()
,Angular 的库中不支持该方法。
虽然我建议您检查问题以了解更多详细信息,但下面的代码也应该为您提供可能的解决方法,如果您真的需要使用转换器,它可能会对您有所帮助。
getCollectionWithConverter(): CollectionReference {
return this.db.firestore.collection("<collection>").withConverter(this.converter)
}
createCourse(course: Course) {
return this.db.collection(this.getCollectionWithConverter()).add(course);
}
除此之外,您可以在以下文章中获得有关如何获取数据并将其映射到对象的最佳实践和示例。
推荐阅读
- ruby-on-rails - 创建记录时,从关联记录中复制属性
- javascript - 为什么 onmouseenter(this) 事件返回的对象的子对象在以某种方式使用时会变为 null?
- django - 如何在跟踪以前的项目的同时从 Django 的列表中返回一个新的非重复项目?
- azure-devops - 使用私有访问令牌时 Azure DevOps 和 Git 授权不起作用
- python - 如何在 Python 中修复字符串索引超出范围异常
- bash - 如何在使用tail、while、read和的shell脚本中检测非滚动日志文件和模式匹配?
- ada - How do I turn off text overwriting when using gnatmake/GPS for ada?
- linux - 如何禁用yocto中的某些键盘键
- python-3.x - 如何在 2 小时后运行 AWS Lambda
- python - * 参数的迭代工具