Function DocumentReference.set() called with invalid data. Unsupported field value: a custom Budget object

前端 未结 5 1289
青春惊慌失措
青春惊慌失措 2020-12-08 07:01

Below code works fine until today. But I don\'t know now it is not working and gives below error.Could you tell me why?

Error: Function DocumentRefere

5条回答
  •  长情又很酷
    2020-12-08 07:29

    You have to transform your array of budgets into an array of pure JavaScript objects.

    First step:

    const budgets = arrayOfBudget.map((obj)=> {return Object.assign({}, obj)});
    

    Second step:

    const proj: Project = {
          id: data.id,
          name: data.name,
          budgetList: budgets
        }
    

    Then you are good to go.

    By the way, when developing with a language that compiles to JavaScript you cannot use custom Objects. Instead, you have to use pure JavaScript objects to save in the Firestore Database.

    For example, let's say you have this class below:

    export class User {
            id: string;
            name: string;
        }
    

    And you try to execute the following code:

     const user = new User();   
     this.db.collection('users').doc().set(user)
    

    You will get an error like:

    invalid data. Data must be an object, but it was: a custom User object

    Now if you try to execute this other line of code:

     this.db.collection('users').doc().set(Object.assign({}, user))
    

    You will see that your object was saved in the database. Basically Object.assign does the same thing as:

    this.db.collection('users').doc().set({id: user.id , name: user.name})
    

    So make use of Object.assign, it will save you a lot of time.

    UPDATE

    As I have pointed out in a comment below, you can find what documentation says about Custom objects here. As you can see, there is a warning saying:

    // Web uses JavaScript objects

    Below there is a screenshot of what the documentation says.

提交回复
热议问题