【问题标题】:mongoose inheritance of statics methods静态方法的猫鼬继承
【发布时间】:2014-07-15 15:10:16
【问题描述】:

我在 Node.js 应用程序中使用 Mongoose,我想使用模型继承。我正在按照此处给出的说明进行操作 Inheritance in mongoose 和其他链接,但我不知道如何继承静态方法。

这是我的尝试:

// The BaseSchema class :
function BaseSchema(objectName, schema) {
    log.trace('BaseSchema CTOR : objectName=%s schema=%s', objectName, schema);
    Schema.apply(this, [schema]);

    var _objectName = objectName;
...
}
BaseSchema.prototype = new Schema();
BaseSchema.prototype.constructor = BaseSchema;

// !!! Here I try to expose the removeAll statics methods for all sub-schema !!!
BaseSchema.prototype.removeAll = function() { ... }

这里是继承的类

// The inherited class
var AccountSchema = new BaseSchema('account', {
...
}
mongoose.model('Account', AccountSchema);

pb 是每次我尝试使用 removeAll 功能。例如:

var Account = mongoose.model('Account');
Account.removeAll(function () {
            done();
        });    

我收到此错误消息:

TypeError: Object function model(doc, fields, skipId) {
    if (!(this instanceof model))
      return new model(doc, fields, skipId);
    Model.call(this, doc, fields, skipId);
  } has no method 'removeAll'

我尝试了不同的组合来声明 removeAll 方法但没有成功:

BaseSchema.prototype.statics.removeAll = function() { ... }
BaseSchema.statics.removeAll = function() { ... }

提前感谢您的帮助!

JM.

【问题讨论】:

    标签: node.js mongodb inheritance mongoose


    【解决方案1】:

    我昨天遇到了同样的问题,最后做了这样的事情:

    var Schema = require('mongoose').Schema;
    
    function AbstractSchema() {
        Schema.apply(this, arguments);
    
        this.add({
            name: String,
            // ...your fields
        });
    
        this.statics.removeAll = function(){
            this.remove({}).exec();
            // ... your functionality
        };
    }
    

    然后创建您的模型;mongoose.model('MyModel', new AbstractSchema())MyModel.removeAll(); 应该可以工作!

    【讨论】:

    • 感谢您的回答。效果很好!只是一个限制:在这种情况下,您为每个实例创建一个新函数,而不是附加到类的函数。我不明白为什么原型方法不起作用。使用原型方法,您只有一个代码(例如,测试覆盖率更好)。
    • 我将发布另一个关于伊斯坦布尔测试覆盖率不准确的问题:stackoverflow.com/questions/23904568/…。非常感谢 ypu 解决方案!
    • 我知道这不是最好的解决方案,但很高兴它能帮到你!
    • @Nick,'this' 指的是什么? -- 我得到:“TypeError: Object # has no method 'add'”,如果我把它注释掉,我得到 - “OverwriteModelError: Cannot overwrite Sample model 一旦编译”,我错过了什么吗?
    • 请解释答案中包含哪些参数。否则也没多大意义,this.add方法用在哪里?非常不完整的答案,希望看到更新
    猜你喜欢
    • 2012-12-23
    • 2015-03-06
    • 2012-06-21
    • 2015-03-20
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 2020-09-11
    • 2017-02-07
    相关资源
    最近更新 更多