Angular17使用ngx-editor出现CastError字符串转换失败问题求助
我在使用Angular 17开发时,用普通textarea绑定brand.promoMaterial能正常保存数据:
<textarea [(ngModel)]="brand.promoMaterial" name="promoMaterial" id="promoMaterial"></textarea>
我的Mongoose Schema中,promoMaterial被定义为string类型:
const BrandSchema = new Schema({ brandDate:{ type: Date }, promoMaterial:{ type:String } })
但换成ngx-editor组件后,保存时出现500错误:
<div class="NgxEditor__Wrapper"> <ngx-editor-menu [editor]="promoMaterial" [toolbar]="toolbar"> </ngx-editor-menu> <ngx-editor [editor]="promoMaterial" [(ngModel)]="brand.promoMaterial" [disabled]="false" [placeholder]="'Type here...'"></ngx-editor> </div>
错误信息如下:
{ "status": "failed", "error": { "message": "Cast to string failed for value \"{\n type: 'doc',\n content: [ { type: 'paragraph', attrs: [Object], content: [Array] } ]\n}\" (type Object) at path \"promoMaterial\"", "stack": "CastError: Cast to string failed for value \"{\n type: 'doc',\n content: [ { type: 'paragraph', attrs: [Object], content: [Array] } ]\n}\" (type Object) at path \"promoMaterial\"\n at model.Query.exec (/home/app/node-board/node_modules/mongoose/lib/query.js:4921:21)\n at Query.then (/home/app/node-board/node_modules/mongoose/lib/query.js:5020:15)" } }
我的TS文件代码:
import { Editor, Toolbar, toHTML, toDoc} from 'ngx-editor'; export class brandComponent implements OnInit{ toolbar: Toolbar = [ ['bold', 'italic', 'underline', 'strike'], ['ordered_list', 'bullet_list'], ]; public brand = {} as Brand; public promoMaterial = new Editor(); constructor( private coreService: CoreService, ){ } }
问题原因
核心原因是ngx-editor默认通过[(ngModel)]绑定的是JSON格式的富文档对象,而非纯字符串。你的Mongoose Schema定义promoMaterial为string类型,保存时Mongoose无法将这个复杂对象转换为字符串,因此抛出类型转换错误。
普通textarea绑定的是纯文本/字符串,和Schema的类型完全匹配,所以能正常保存;但ngx-editor绑定的是它内部的文档结构(即错误信息中显示的{type: 'doc', content: [...]}对象),与你定义的string类型冲突,导致保存失败。
解决方案
方案1:将文档对象转为HTML字符串保存
提交数据前,使用ngx-editor提供的toHTML()方法将文档对象转换为HTML字符串,再赋值给brand.promoMaterial:
// 提交数据前执行转换 this.brand.promoMaterial = toHTML(this.promoMaterial.getDocument());
如果需要从后端获取数据并回显到编辑器,还要用toDoc()方法把HTML字符串转回文档对象:
// 获取后端数据后回显到编辑器 this.promoMaterial.setDocument(toDoc(this.brand.promoMaterial));
方案2:修改Mongoose Schema类型
如果你希望直接保存ngx-editor的文档对象,可以把Schema中的promoMaterial类型改为Object或Schema.Types.Mixed:
const BrandSchema = new Schema({ brandDate:{ type: Date }, promoMaterial:{ type: Object // 或 Schema.Types.Mixed } })
不过这种方式后续处理富文本内容时需要自行解析对象,不如保存HTML字符串直观易用。
内容的提问来源于stack exchange,提问作者Elaine Byene

