我在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。
答案 0 :(得分: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();
就可以了!