Firestore-使用数组添加对象 [英] Firestore - adding object with an array

查看:53
本文介绍了Firestore-使用数组添加对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

整天在这里用这东西杀死自己,我上了两门课,分别是Department和Articals:

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

like您可以看到部门包含"Articles"数组因此,我正在使用新的艺术品(及其属性)建立新的部门,并尝试通过以下方式将其添加到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));

但出现错误:使用无效数据调用了Function 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});

并使用'update'而不是'set'但没有帮助: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.

首先更改您的部门课程:

First change your Department class:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆