This is my controller class. where i want to convert data to my custom object
getRegister(node:string) {
this.db.firestore.collection('databasetable')
.where('profileId','==', node)
.get()
.then(querySnapshot => {
querySnapshot.forEach(function (doc) {
console.log(doc.id); // id of doc
console.log(doc.data()); // data of doc
//Want to cast my object here for displaying into UI
})
});
}
The data() method always returns a JSON object. I think you're looking for the (relatively recent) withConverter methods and FirestoreDataConverter class:
await firebase.firestore()
.collection('posts')
.withConverter(postConverter) // 👈 this is a custom class that performs the conversion
.doc().get();
The postConverter above is an object that has toFirestore and fromFirestore methods to convert the JSON from/to the custom class, for example:
const postConverter = {
toFirestore(post: Post): firebase.firestore.DocumentData {
return {title: post.title, author: post.author};
},
fromFirestore(
snapshot: firebase.firestore.QueryDocumentSnapshot,
options: firebase.firestore.SnapshotOptions
): Post {
const data = snapshot.data(options)!;
return new Post(data.title, data.author);
}
};
Also see the documentation for the DocumentReference.withConverter method and the FirestoreDataConverter class, where I got the above code samples from.