0

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.

3
  • 7
    Your toJSON function returns an object. You really need to learn the difference between JSON and JavaScript objects so that you can ask a clear question. Commented Aug 20, 2018 at 14:43
  • 2
    I guess you actually did console.log(entry.toJSON) instead of console.log(entry.toJSON()) Commented Aug 20, 2018 at 14:47
  • @JonasWilms damn your right, that was actually my problem. Commented Aug 20, 2018 at 14:53

2 Answers 2

1

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)) };
 }
Sign up to request clarification or add additional context in comments.

2 Comments

You may want to include some documentation (e.g. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…) with this answer. A nooby javascript user may not know what a getter is
Damn now I feel stupid, I forgot the () as you mentioned. Also I had to change the method a little bit, I awserded below
0

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.