从Mongoose迁移至Typegoose:子文档初始化简化方案咨询
问题描述
我们正将项目从纯Mongoose迁移至Typegoose,整体体验良好,但存在一个困扰我们的问题。
假设有一个简单模型:
class Animal { @prop() public name?: string; } const AnimalModel = getModelForClass(Animal);
此时创建新条目只需执行:
await AnimalModel.create({ name: 'Kitty' });
但添加子文档后:
class Animal { @prop() public name?: string; @prop() public properties?: Properties; } class Properties { @prop() public hasEaten?: boolean; }
初始化操作变得繁琐:
const props = new Properties(); props.hasEaten = true; await AnimalModel.create({ name: 'Kitty', properties: props });
我们了解可以使用Passthrough Class,但该方法并不推荐。请问有什么方法可以简化子文档的创建流程?
简化子文档创建的方法
1. 启用allowMixed选项直接传字面量
Typegoose默认限制直接传入普通对象作为子文档,你可以通过配置allowMixed: Severity.ALLOW解除这个限制。
先在模型类上添加配置:
import { prop, getModelForClass, modelOptions, Severity } from "@typegoose/typegoose"; @modelOptions({ schemaOptions: { allowMixed: Severity.ALLOW } }) class Animal { @prop() public name?: string; @prop() public properties?: Properties; } class Properties { @prop() public hasEaten?: boolean; }
之后就能像Mongoose一样直接传入子文档字面量:
await AnimalModel.create({ name: 'Kitty', properties: { hasEaten: true } });
2. 给子文档类添加静态创建方法
在子文档类里封装一个静态方法,快速生成实例:
class Properties { @prop() public hasEaten?: boolean; public static from(data: Partial<Properties>) { const instance = new Properties(); Object.assign(instance, data); return instance; } }
使用时只需调用这个方法:
await AnimalModel.create({ name: 'Kitty', properties: Properties.from({ hasEaten: true }) });
3. 使用类型断言快速兼容
如果不想修改配置或添加方法,用类型断言告诉TypeScript字面量符合子文档类型即可:
await AnimalModel.create({ name: 'Kitty', properties: { hasEaten: true } as Properties });
这种方式轻量快捷,但要确保传入的字段和子文档类定义一致,避免运行时出错。
内容的提问来源于stack exchange,提问作者shem
相关产品推荐
相关产品推荐

