如何使用TypeScript创建Mongoose Schema并为数组类型字段设置默认值
存在的问题
- 类型不匹配:你在TypeScript接口
IUser中定义了business是IBusinessShort类型的数组,但Mongoose Schema里仅指定business为普通Array,没有声明数组元素的结构,Mongoose不会对数组内的字段做校验,也无法和TS类型做对应,后续写入不符合IBusinessShort结构的数据也不会触发报错,容易产生脏数据。 - 类型推断失效:由于Schema层没有定义数组元素类型,后续使用这个Schema做增删改查操作时,Mongoose无法正确给
business字段做TS类型推断,会丢失类型提示。
修正方案
你需要为business字段定义匹配IBusinessShort的子Schema结构,示例代码如下:
export interface IBusinessShort{ savedOn: string; } // 先定义IBusinessShort对应的子Schema const BusinessShortSchema = new Schema<IBusinessShort>({ savedOn: { type: String, required: true } }) export interface IUser { name: string; email: string; username: string; password: string; phoneNumber: string; avatar?: string; business: Array<IBusinessShort>; } const schema = new Schema<IUser>({ name: { type: String, required: true }, email: { type: String, required: true }, username: { type: String, required: true }, password: { type: String, required: true }, phoneNumber: { type: String, required: true }, avatar: String, // 指定数组元素类型为刚才定义的子Schema,保留默认空数组配置 business: { type: [BusinessShortSchema], default: []}, });
如果你的IBusinessShort后续还有扩展字段,只需要同步更新BusinessShortSchema即可保证TS类型和Mongoose校验规则一致。
内容的提问来源于stack exchange,提问作者Dipanshu Mahla
相关产品推荐
相关产品推荐

