Firestore, being a noSQL database, is schemaless. However, I want to ensure that the correct data type is being passed in.
Custom Objects As per Firebase documentation, https://firebase.google.com/docs/firestore/manage-data/add-data
class City {
constructor ( name, state, country ) {
this.name = name;
this.state = state;
this.country = country;
}
toString() {
return this.name + ', ' + this.state + ', ' + this.country;
}
}
// Firestore data converter
const cityConverter = {
toFirestore: (city) => {
return {
name: city.name,
state: city.state,
country: city.country
};
},
fromFirestore: (snapshot, options) => {
const data = snapshot.data(options);
return new City(data.name, data.state, data.country);
}
};
which then they do:
const ref = doc(db, "cities", "LA").withConverter(cityConverter);
await setDoc(ref, new City("Los Angeles", "CA", "USA"));
In my case, I am also utilizing TypeScript in the constructor to ensure developers provide the correct inputs:
constructor ( name : String , state : String, country : String )
Firebase Rules Alternatively, there is another method, mentioned in this post, How can I enforce database schema in Firestore? using the firebase rule system.
I have personally only experimented with the "custom objects" approach which has worked well, enforcing developers to catch errors early related to incorrect data types.
So, what specific advantages does the firebase rule system offer?
In my current small project, would the rule system be preferable in a production environment since it offers more concealment?