Mongoose中子文档为何可能为undefined?如何确保其非空非未定义?
解决Mongoose子文档类型推断包含null/undefined的问题
要确保sub字段不会被推断为null或undefined,可以通过以下几种Schema配置方式实现:
1. 强制字段必填
给sub字段添加required: true,明确要求该字段必须存在,TypeScript推断时会自动排除undefined和null类型:
const someSchema = new Schema( { sub: { type: { val: { type: String, default: "" }, }, required: true // 强制sub字段必须存在 }, // 其他属性... } ); type Doc = InferSchemaType<typeof someSchema>; // 此时Doc的sub类型为:{ val: string }
2. 设置默认值
给sub字段配置默认值,确保即使创建文档时未传入该字段,Mongoose也会自动填充默认的子文档对象,同时类型推断会排除null/undefined:
const someSchema = new Schema( { sub: { type: { val: { type: String, default: "" }, }, default: () => ({}) // 默认生成空对象,或直接写{ val: "" } }, // 其他属性... } ); type Doc = InferSchemaType<typeof someSchema>; // 此时Doc的sub类型为:{ val: string }
注意事项
- 嵌套子文档时,建议明确指定
type字段包裹子结构,避免Mongoose对类型推断产生歧义。 - 确保你的Mongoose版本支持
InferSchemaType的正确类型推导(建议使用v6及以上版本)。
内容的提问来源于stack exchange,提问作者favicon thief
相关产品推荐
相关产品推荐

