十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

Mongoose 高级 Schema 实战:用 `loadClass()` 从 ES6 类构建 Schema 的完整指南

Mongoose 高级 Schema 实战:用 `loadClass()` 从 ES6 类构建 Schema 的完整指南 Mongoose 高级 Schema 实战用loadClass()从 ES6 类构建 Schema 的完整指南【免费下载链接】mongooseMongoDB object modeling designed to work in an asynchronous environment.项目地址: https://gitcode.com/GitHub_Trending/mo/mongoose本篇技术指南以 docs/advanced_schemas.md 为核心系统讲解 Mongoose 中schema.loadClass()的用法与底层原理。你将掌握如何把 ES6 类的实例方法、静态方法与 getter/setter 分别映射为 Mongoose 的 methods、statics 与 virtuals理解其继承处理与 TypeScript 类型配合的注意事项并能在真实项目中直接落地这套以类驱动 Schema的开发模式。loadClass()是什么用 ES6 类一键装载 SchemaMongoose 允许通过 ES6 类来构建 Schema。loadClass()是挂在Schema.prototype上的方法它的作用是把一个 ES6 类中的成员搬运到 Schema 上映射规则非常直观ES6 类成员映射目标对应 Schema 能力实例方法method() {}Schema methods文档document方法静态方法static method() {}Schema statics模型Model方法getter / setterget x()/set x(v)Schema virtuals虚拟属性该方法的官方类型声明位于 types/index.d.tsloadClass(model: Function, onlyVirtuals?: boolean): this其中第二个可选参数onlyVirtuals源码中也写作virtualsOnly若为真值则只装载 virtuals不装载 methods 与 statics。完整示例从 PersonClass 创建 Person 模型以下示例完整继承自 docs/advanced_schemas.md同时它也是仓库中 test/docs/schemas.test.js 的真实测试用例可直接运行验证const schema new Schema({ firstName: String, lastName: String }); class HumanClass { get fullName() { return My name; } } class PersonClass extends HumanClass { // fullName 成为 virtual虚拟属性 get fullName() { return ${super.fullName} is ${this.firstName} ${this.lastName}; } set fullName(v) { const firstSpace v.indexOf( ); this.firstName v.split( )[0]; this.lastName firstSpace -1 ? : v.substring(firstSpace 1); } // getFullName() 成为文档方法method getFullName() { return ${this.firstName} ${this.lastName}; } // findByFullName() 成为静态方法static static findByFullName(name) { const firstSpace name.indexOf( ); const firstName name.split( )[0]; const lastName firstSpace -1 ? : name.substring(firstSpace 1); return this.findOne({ firstName, lastName }); } } schema.loadClass(PersonClass); const Person db.model(Person, schema); const doc await Person.create({ firstName: Jon, lastName: Snow }); assert.equal(doc.fullName, My name is Jon Snow); doc.fullName Jon Stark; assert.equal(doc.firstName, Jon); assert.equal(doc.lastName, Stark); const foundPerson await Person.findByFullName(Jon Snow); assert.equal(foundPerson.fullName, My name is Jon Snow);代码中的关键点逐一说明fullNamegetter/setter 成对存在因此fullName被注册为一个可读可写的 virtual。读取时执行 getter拼接super.fullName与文档字段赋值时执行 setter把Jon Stark拆回firstName/lastName两个真实字段。赋值doc.fullName Jon Stark后doc.firstName Jon、doc.lastName Stark正是 setter 生效的证据。getFullName()成为文档方法可在实例上直接调用。findByFullName()成为静态方法注意它内部使用this.findOne(...)这里的this指向模型本身因此可以用链式查询能力。映射规则的底层实现从源码看loadClass()做了什么loadClass()的完整实现位于 lib/schema.js核心逻辑可以拆解为三步1. 沿原型链递归装载支持继承Schema.prototype.loadClass function(model, virtualsOnly) { // 停止拷贝的基线遇到 Object/Function 原型或带 Mongoose 标记的原型 if (model Object.prototype || model Function.prototype || Object.hasOwn(model.prototype, $isMongooseModelPrototype) || Object.hasOwn(model.prototype, $isMongooseDocumentPrototype)) { return this; } this.loadClass(Object.getPrototypeOf(model), virtualsOnly); ...函数会先递归处理Object.getPrototypeOf(model)再处理当前类自身。这意味着继承链上的成员会被依次装载——示例中PersonClass extends HumanClassHumanClass的fullNamegetter 也会先被注册随后被子类同名 getter 覆盖这正是super.fullName能取到My name的原因。仓库测试 test/schema.test.js 中handles loadClass with inheritted getters (gh-9975)专门验证了这一行为。同时递归的终止条件会检查$isMongooseModelPrototype与$isMongooseDocumentPrototype标记确保当传入的类继承自 Mongoose 的Model或Document时不会把内部实现误拷进 Schema对应 lib/helpers/model/applyMethods.js 中 gh-12254 的防护逻辑。2. 静态方法从类自身属性装载// Add static methods if (!virtualsOnly) { Object.getOwnPropertyNames(model).forEach(function(name) { if (name.match(/^(length|name|prototype|constructor|__proto__)$/)) { return; } const prop Object.getOwnPropertyDescriptor(model, name); if (Object.hasOwn(prop, value)) { this.static(name, prop.value); } }, this); }这里遍历类自身的属性名Object.getOwnPropertyNames而非for...in只取自有属性跳过length、name、prototype、constructor、__proto__等内建成员然后通过this.static(name, value)注册。注意它只处理拥有value属性描述符的成员——像static get x()这种静态 getter 会被跳过仓库测试 test/schema.test.js 专门覆盖了loadClass with static getter (gh-10436)场景。3. 实例方法与 virtuals从原型装载Object.getOwnPropertyNames(model.prototype).forEach(function(name) { if (name.match(/^(constructor)$/)) { return; } const method Object.getOwnPropertyDescriptor(model.prototype, name); if (!virtualsOnly) { if (typeof method.value function) { this.method(name, method.value); } } if (typeof method.get function) { if (this.virtuals[name]) { this.virtuals[name].getters []; } this.virtual(name).get(method.get); } if (typeof method.set function) { if (this.virtuals[name]) { this.virtuals[name].setters []; } this.virtual(name).set(method.set); } }, this);遍历model.prototype的自有属性并跳过constructor普通函数method.value是函数→ 注册为文档方法this.method(name, value)gettermethod.get是函数→ 注册为 virtual 的 gettersettermethod.set是函数→ 注册为 virtual 的 setter。一个值得注意的细节如果同名 virtual 已存在源码会先清空旧的getters/setters数组再重新注册保证子类覆盖父类同名成员时行为正确。快速验证装载后 schema 上有什么docs/guide.md 中给出了一个最小化的验证方式class MyClass { myMethod() { return 42; } static myStatic() { return 42; } get myVirtual() { return 42; } } const schema new mongoose.Schema(); schema.loadClass(MyClass); console.log(schema.methods); // { myMethod: [Function: myMethod] } console.log(schema.statics); // { myStatic: [Function: myStatic] } console.log(schema.virtuals); // { myVirtual: VirtualType { ... } }loadClass()的第二种出场方式继承Model的类除了显式调用schema.loadClass(cls)Mongoose 在传入的模型本身就是继承自Model的类时会在编译阶段自动装载。见 lib/model.js 的Model.compileModel.compile function compile(name, schema, collectionName, connection, base) { ... if (typeof name function name.prototype instanceof Model) { model name; name model.name; schema.loadClass(model, false); model.prototype.$isMongooseModelPrototype true; } else { // 生成新的模型类 }也就是说当你把继承自Model的类直接交给mongoose.model()时compile内部会自动调用schema.loadClass(model, false)并把类的原型标记为$isMongooseModelPrototype。这个标记同时会作为loadClass递归的终止条件避免链条继续向上追溯到 Mongoose 内部的Model.prototype。仓库测试 test/model.test.js 的 works if passing class that extends Document toloadClass()(gh-12254) 验证了类继承Document时的兼容行为。TypeScript 场景下的loadClass()类型需要手动补全loadClass()在运行时能完整搬运类成员但它不会自动更新 TypeScript 类型。官方在 docs/typescript/statics-and-methods.md 中明确了这一点并在 test/types/loadclass.test.ts 中用 tstyche 类型断言固化了几条规则1. 手动组合类型因为类型不自动推导需要把 Schema 字段与类成员手动合并class MyClass { myMethod() { return 42; } static myStatic() { return 42; } get myVirtual() { return 42; } } const schema new Schema({ property1: String }); schema.loadClass(MyClass); interface MySchema { property1: string; } // loadClass() 不会自动更新 TS 类型必须手动合并 type MyCombined MySchema MyClass; type MyCombinedModel ModelMyCombined typeof MyClass; type MyCombinedDocument Document MyCombined; const MyModel modelMyCombinedDocument, MyCombinedModel(MyClass, schema as any); MyModel.myStatic(); // 静态方法可用 new MyModel().myMethod(); // 实例方法可用2.this参数的显式标注实例方法与静态方法可以在类中通过this参数标注真实的文档/模型类型但TypeScript 不允许 getter/setter 声明this参数getter 内访问 Schema 字段会被推断为anytest/types/loadclass.test.ts。3.toObject()/toJSON()会丢失类行为doc.toObject()返回的是纯对象POJO运行时不再有myMethod等方法但 TypeScript 仍认为方法存在——这是一个编译期无法暴露的类型陷阱对应 issue #12813见 test/types/loadclass.test.ts。从loadClass()构建的文档做toObject()/toJSON()后不要调用类方法也不要对返回值调用类 getter。使用建议与边界何时用loadClass()当你偏爱面向对象风格、想把领域逻辑方法、静态查询、计算属性集中写在 ES6 类中时loadClass()是schema.methods/schema.statics/schema.virtual之外的另一种组织方式。官方在 docs/typescript/statics-and-methods.md 的倾向性说明是类风格可用但如果使用 TypeScript更推荐在 Schema 选项中直接定义statics和methods因为可以享受自动类型推导而loadClass()需要手工维护类型且存在toObject()丢失方法的隐患。virtualsOnly参数当只需要类的 getter/setter比如把类的计算属性映射为 virtual 而不要方法时可传true跳过 methods 与 statics 的装载。继承层级loadClass()会沿原型链递归装载子类同名成员覆盖父类若类继承自Model/DocumentMongoose 的内部原型会被自动识别并跳过。验证路径文档中的示例即仓库测试 test/docs/schemas.test.js围绕 loadClass 的行为回归测试分布在 test/schema.test.js、test/model.test.js 与 test/document.test.js 中类型层面由 test/types/loadclass.test.ts 把关可作为你理解与复现行为的直接参考。【免费下载链接】mongooseMongoDB object modeling designed to work in an asynchronous environment.项目地址: https://gitcode.com/GitHub_Trending/mo/mongoose创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表