gpt4 book ai didi

angular - 使用无效数据调用函数 DocumentReference.set()。不支持的字段值 : a custom Budget object

转载 作者:太空狗 更新时间:2023-10-29 16:50:33 25 4
gpt4 key购买 nike

下面的代码直到今天都可以正常工作。但我现在不知道它不工作并给出以下错误。你能告诉我为什么吗?

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

 export class Project {
id: string = null;
name: string;
budgetList?: Budget[];
}

export class Budget {
id: string;
amount: number;
contingency: number = 20;
budgetGroup: BudgetGroup = new BudgetGroup();
creationTime: string;
}

代码:

  async create(data: DtoProject): Promise<Project> {
try {
const projectId: string = this.fireStore.createId();
const budgets = this.budgetProvider.createBudgets(data.budgetList, projectId);//budgets
const proj: Project = {
id: data.id,
name: data.name,
budgetList: budgets,//here it has the error
}
proj.id = projectId;
await this.fireStore.doc<Project>(`projects/${projectId}/`).set(proj));//project
}
}

createBudgets(data: Budget[], projectId: string): Budget[] {
let budgets: Budget[] = [];
forEach(data, (d) => {
const budgetId: string = this.fireStore.createId();
d.id = budgetId;
budgets.push(d);
this.fireStore.doc<Budget>(`projects/${projectId}/budgets/${budgetId}`).set({
id: budgetId,
amount: d.amount,
contingency: d.contingency,
budgetGroup: d.budgetGroup,
creationTime: moment().format()
})
})
return budgets;
}

最佳答案

您必须将预算数组转换为纯 JavaScript 对象数组

第一步:

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

第二步:

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

那么你就可以开始了。

顺便说一句,当使用编译为 JavaScript 的语言进行开发时,您不能使用自定义对象。相反,您必须使用纯 JavaScript 对象来保存在 Firestore 数据库中。

例如,假设您有下面这个类:

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

然后您尝试执行以下代码:

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

你会得到这样的错误:

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

现在,如果您尝试执行另一行代码:

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

您将看到您的对象已保存在数据库中。基本上 Object.assign 做同样的事情:

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

所以利用Object.assign,它会为你节省很多时间。

更新

正如我在下面的评论中指出的,您可以找到有关自定义对象 的文档here .如您所见,有一条警告说:

// Web uses JavaScript objects

下面是文档内容的屏幕截图。

enter image description here

关于angular - 使用无效数据调用函数 DocumentReference.set()。不支持的字段值 : a custom Budget object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48156234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com