Reputation: 7885
In need to add an Object to my Firestore database. It only takes JSON objects. However I also want to exclude some fields of my object to not get send to my database.
So I added a function that should return a JSON like this:
export class Entry {
date: number;
timeStart: number;
timeEnd: number;
entry: EntryData;
// To be excluded from database
selected: boolean;
constructor(date: number, timeStart: number, timeEnd: number, entry: EntryData) {
this.date = date;
this.timeStart = timeStart;
this.timeEnd = timeEnd;
this.entry = entry;
}
toJSON() {
return {date: this.date, timeStart: this.timeStart, timeEnd: this.timeEnd, entry: JSON.parse(JSON.stringify(this.entry)) };
}
}
However when I do console.log(entry.toJSON())
I get this:
workday.service.ts:122 ƒ () {
return { date: this.date, timeStart: this.timeStart, timeEnd: this.timeEnd, entry: JSON.parse(JSON.stringify(this.entry)) };
}
I want to use the function like this:
this.employeeRef.collection('Entries').add(entry.toJSON);
But that doesn't work. It works like this:
this.employeeRef.collection('Entries').add(JSON.parse(JSON.stringify(entry)));
But this way the selected
field is not excluded from the database.
Any Ideas? Note that I'm using TypeScript (with Angular) but I think thats a pure JavaScript problem.
Upvotes: 0
Views: 117
Reputation: 7885
This seems to work:
toJSON() {
return {date: this.date, timeStart: this.timeStart, timeEnd: this.timeEnd, entry: JSON.parse(JSON.stringify(this.entry)) };
}
I can use it like this:
his.employeeRef.collection('Entries').add(entry.toJSON());
Upvotes: 0
Reputation: 138297
You probably want to use a getter:
get toJSON() {
return {date: this.date, timeStart: this.timeStart, timeEnd: this.timeEnd, entry: JSON.parse(JSON.stringify(this.entry)) };
}
Upvotes: 1