Firestore - 添加带有数组的对象 [英] Firestore - adding object with an array
问题描述
整天在这里用这东西杀死自己,我有两个课程部门和文章:
killing myself with this thing in here all day, I'm having two classes Department and Articals :
export class Department {
articals?: Artical[]=[];
moms?: number;
id?: string;
constructor() {
}
}
和:
export class Artical {
moms?: number;
price: number;
name?: string;
constructor() {
}
}
喜欢你可以看到部门包含一个文章"数组所以我正在用新的文章(及其属性)建立新的部门,并尝试将其添加到 fireStore 中:
like You can see departments contains an Array of 'Articals' so I am building new Department with new articals(and their properties) and trying to add it to fireStore with:
this.departmetsCollection.doc(departmentId).set(Object.assign({},
myDepartment));
但收到错误:使用无效数据调用函数 DocumentReference.set().不支持的字段值:自定义 Artical 对象"
but getting Error : "Function DocumentReference.set() called with invalid data. Unsupported field value: a custom Artical object"
P.s 尝试只将文章数组添加到部门路径中
P.s tryed add only array of articals to the path of department as
doc(departmentId).set({'articals':myArticals});
并且使用更新"而不是设置"但也没有帮助:S将这种对象添加到 firestore 中的正确做法是什么?
and with 'update' instead of 'set' but no help either:S what is teh correct of adding that kind of object to firestore?
推荐答案
Firestore 只接受嵌入在文档中的 JavaScript 对象,前提是它是纯"对象,这意味着在 TypeScript 中开发时不能使用自定义对象.因此,您必须先映射您的对象,然后再将它们推送到 articals 数组.
Firestore only accepts a JavaScript object embedded within a document if it is a "pure" object, this means you can't use custom objects while developing in TypeScript. So you would have to map your objects before push them to the articals array.
首先改变你的系类:
export class Department {
articals?: Array<any>=[];
moms?: number;
id?: string;
constructor() {
}
}
第二个映射你的Artical"数组:
Second map your array of "Artical":
var map = arrayOfArtical.map((obj)=> {return Object.assign({}, obj)});
然后您可以将地图值归因于'this.myDepartment.articals'
Then you can attribute the map value to 'this.myDepartment.articals'
this.myDepartment.articals = map;
之后就可以执行了:
this.departmetsCollection.doc(departmentId).set(Object.assign({},
myDepartment))
这篇关于Firestore - 添加带有数组的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!