首页 > 解决方案 > “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)
      });

    }

除了解决这个错误,我想知道存储和检索这样的数据的最佳实践。谢谢!

标签: angularfirebasegoogle-cloud-firestoreangularfire

解决方案


如本期所述,它在 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);
}

除此之外,您可以在以下文章中获得有关如何获取数据并将其映射到对象的最佳实践和示例。


推荐阅读