Mongoose 静态方法的继承

3
我在一个Node.js应用程序中使用Mongoose,并希望使用模型的继承。我正在遵循这里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);

问题在于每次我尝试使用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。
1个回答

5

昨天我也遇到了同样的问题,最终做了类似于这样的操作:

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(); 就可以工作了!


谢谢你的回答。它非常有效!只是有一个限制:在这种情况下,您为每个实例创建一个新函数,而不是附加到类的函数。我不明白为什么原型方法不起作用。使用原型方法,您只有一个代码(例如,测试覆盖率更好)。 - jmcollin92
我将发布另一个问题,针对这种方法: https://dev59.com/r4Daa4cB1Zd3GeqP_xgf,伊斯坦布尔测试覆盖率不准确。非常感谢您的解决方案!! - jmcollin92
我知道这不是最好的解决方案,但我很高兴它能帮助到你! - Nick
@Nick,"this" 是指什么?如果我将其注释掉,我会得到 "TypeError: Object #<AbstractSchema> has no method 'add'" 的错误提示,如果我不注释掉,我会得到 "OverwriteModelError: Cannot overwrite Sample model once compiled" 的错误提示,我是不是漏掉了什么? - Aviram Netanel
请解释答案中的arguments是什么。否则,它就没有太多意义。this.add方法在哪里使用?非常不完整的答案,希望看到更新。 - mibbit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接