node.js - 如何使用静态方法扩展类?

标签 node.js static typescript

我想使用静态函数扩展我的 UserModel.model 对象。我该怎么做?

正如你在下面看到的,我的UserModel.model是一个 Mongoose 模型对象,但我需要向这个对象添加方法,重点是:我不知道如何编写它。我无法像 Java/C# 中那样使用 static{} 区域来执行静态代码,我找不到编写它的方法。你是吗?

例如,我想添加诸如 existsconnect 等方法。

///<reference path='../../lib/def/defLoader.d.ts'/>

import model = require('./Model');

export module Models {
    export class UserModel extends model.Models.Model implements model.Models.IModel{
        /**
         * Name of the model.
         * MUST start by uppercase letter!
         */
        private static modelName: string = 'User';

        /**
         * Public readable schema as object.
         */
        public static schema: any = {
            /**
             * User Login
             */
            login: {
                type: 'string',
                minLength: 4,
                maxLength: 16,
                required: true,
                notEmpty: true,
                unique: true
            }
        };

        /**
         * Private schema as mongoose.Schema type.
         */
        private static _schema: mongoose.Schema = new mongoose.Schema(UserModel.schema);

        /**
         * The mongoose model that uses the mongoose schema.
         */
        public static model: mongoose.Model<any> = mongoose.model(UserModel.modelName, UserModel._schema);



        /**
         *************************************************************************************************
         *********************************** Public (Helpers) ********************************************
         *************************************************************************************************
         */

        /**
         * Name of the model.
         * MUST start by uppercase letter!
         */
        public modelName: string;

        /**
         * Contains the static value of the public schema as object.
         * It's a helper to always get the schema, from instance or static.
         */
        public schema: mongoose.Schema;

        /**
         * Contains the static value of the object used to manipulate an instance of the model.
         * It's a helper to always get the model, from instance or static.
         */
        public model: mongoose.Model<any>;

        /**
         * Use static values as instance values.
         */
        constructor(){
            super();

            // Use static values as instance values.
            this.modelName = UserModel.modelName;
            this.schema = UserModel.schema;
            this.model = UserModel.model;
        }

        /**
         *************************************************************************************************
         *********************************** Extended methods ********************************************
         *************************************************************************************************
         */
    }
}

最佳答案

我建议您使用标准 MongooseJS 方式,通过使用 Schema 实例的 statics 属性向模型添加静态方法,如下所示。

module MongooseDemo {
    export class Demo {
        public static LoginSchema: any = {
            /* User Login */
            login: {
                type: 'string',
                minLength: 4,
                maxLength: 16,
                required: true,
                notEmpty: true,
                unique: true
            }
        };      

        public static Model : any; // static store for data 

        constructor() {
            // there is not a concept of a static constructor in  
            // typescript, so static initialization code may be better else
            // where
        }       
    }

    // I've made this an anonymous function that is private to the module
    // It's executed immediately and initializes the "static" values of the 
    // class. this code could be moved into a static method of course and 
    // and called directly in the same way
    (()=> {
        // create the schema defined
        var schema : any = mongoose.Schema(Demo.LoginSchema);
        // add the statics before creating the model
        // http://mongoosejs.com/docs/guide.html#statics
        schema.statics.exists = () => {
           // here's a static method                    
        };
        // create the model
        Demo.Model = mongoose.Model('Demo', schema);

    })();
}

由于 JavaScript 或 Typescript 中没有静态构造函数的概念,因此我在 MongooseDemo 模块内创建了一个匿名函数来自动初始化类的静态字段。您当然可以移动代码,但总体概念应该可行。

或者,您可以在创建模型后直接将静态方法添加到模型中(同样是在匿名方法中):

Demo.Model.exists2 = () => {
    // something different              
};

在 Mongoose 中添加类方法/静态的实际代码非常简单,因为它只是将所有函数(和属性)从 Schema 对象实例的 statics 属性直接复制到新的 Model 中。因此,我提供的第二个示例在功能上等同于我提出的第一种方式,即 documented .

关于node.js - 如何使用静态方法扩展类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20840633/

相关文章:

node.js - 使用 SSL 托管多个 node.js 站点

javascript - 在Windows,Mac(Darwin)和Linux上按进程名称执行 Electron 杀进程

node.js - 使用 Node 请求和 URL 扫描从 CSV 下载图像

javascript - 类型 'number' 不可分配给类型 'ReadonlyArray<{}>'

node.js - Loopback 4 POST 方法给出 422 错误

javascript - 为什么 "script"内的代码在 html 中不起作用?

node.js - socket.on 事件被多次触发

c - 反转数字的递归函数

java - 从jsp访问类的静态字段

C# 使类静态化?