jmc*_*n92 3 inheritance mongoose mongodb node.js
我在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() { ... }
Run Code Online (Sandbox Code Playgroud)
这是继承的类
// The inherited class
var AccountSchema = new BaseSchema('account', {
...
}
mongoose.model('Account', AccountSchema);
Run Code Online (Sandbox Code Playgroud)
pb是每次我尝试使用removeAll函数.例如 :
var Account = mongoose.model('Account');
Account.removeAll(function () {
done();
});
Run Code Online (Sandbox Code Playgroud)
我收到此错误消息:
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'
Run Code Online (Sandbox Code Playgroud)
我尝试使用不同的combinaison来声明removeAll方法但没有成功:
BaseSchema.prototype.statics.removeAll = function() { ... }
BaseSchema.statics.removeAll = function() { ... }
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的帮助 !
JM.
昨天我遇到了同样的问题,结果做了这样的事情:
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
};
}
Run Code Online (Sandbox Code Playgroud)
然后创建你的模型; mongoose.model('MyModel', new AbstractSchema())并MyModel.removeAll();应努力!
| 归档时间: |
|
| 查看次数: |
1302 次 |
| 最近记录: |