Firestore - adding object with an array

久未见 提交于 2021-02-07 08:44:40

问题


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() {
}
}

and:

export class Artical {

moms?: number;
price: number;
name?: string;

constructor() {
}
}

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

but getting Error : "Function DocumentReference.set() called with invalid data. Unsupported field value: a custom Artical object"

P.s tryed add only array of articals to the path of department as

doc(departmentId).set({'articals':myArticals});

and with 'update' instead of 'set' but no help either:S what is teh correct of adding that kind of object to firestore?


回答1:


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.

First change your Department class:

export class Department {
articals?: Array<any>=[];
moms?: number;
id?: string;
constructor() {
}
}

Second map your array of "Artical":

var map = arrayOfArtical.map((obj)=> {return Object.assign({}, obj)});

Then you can attribute the map value to 'this.myDepartment.articals'

this.myDepartment.articals  = map;

After that you can execute:

this.departmetsCollection.doc(departmentId).set(Object.assign({}, 
myDepartment))


来源:https://stackoverflow.com/questions/47190803/firestore-adding-object-with-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!