If you have a FirebaseFirestore.Timestamp
object then don't use JSON.parse(JSON.stringify(obj))
or classToPlain(obj)
as those will corrupt it while storing to Firestore.
It's better to use {...obj}
method.
firestore
.collection('collectionName')
.doc('id')
.set({...obj});
Note: do not use new
operator for any nested objects inside document class, it'll not work. Instead, create an interface
or type
for nested object properties like this:
interface Profile {
firstName: string;
lastName: string;
}
class User {
id = "";
isPaid = false;
profile: Profile = {
firstName: "",
lastName: "",
};
}
const user = new User();
user.profile.firstName = "gorv";
await firestore.collection("users").add({...user});
And if you really wanna store class object consists of deeply nested more class objects then use this function to first convert it to plain object while preserving FirebaseFirestore.Timestamp
methods.
const toPlainFirestoreObject = (o: any): any => {
if (o && typeof o === "object" && !Array.isArray(o) && !isFirestoreTimestamp(o)) {
return {
...Object.keys(o).reduce(
(a: any, c: any) => ((a[c] = toPlainFirestoreObject(o[c])), a),
{}
),
};
}
return o;
};
function isFirestoreTimestamp(o: any): boolean {
if (o &&
Object.getPrototypeOf(o).toMillis &&
Object.getPrototypeOf(o).constructor.name === "Timestamp"
) {
return true;
}
return false;
}
const user = new User();
user.profile = new Profile();
user.profile.address = new Address();
await firestore.collection("users").add(toPlainFirestoreObject(user));
.doc()
to the end of your firestore reference. – Kommunarsk