由于 mongoose 处理它们的方式,以及 mongoose=require('mongoose')
是一个单例,我还没有找到一种简单的方法来扩展 Mongoose Schema/Model 方法.
所以,我在这里“伪造”类继承:
'use strict';
var _ = require('lodash');
module.exports = function(MongooseModel, options) {
var Collection = {};
_.assign(Collection, _.toPlainObject(MongooseModel));
Collection.pluralName = Collection.modelName + 's';
Collection.foo = Collection.bar;
return Collection
};
有没有人有更优雅的解决方案?
编辑:
事实证明上述解决方案不起作用。例如,使用 Collection.find({}, function(err, docs) {...})
会在 Mongo 尝试从尚未注册到 Mongoose 的模型中创建“docs”时出错.
所以,我现在所做的完全不优雅:
'使用严格';
var _ = require('lodash');
module.exports = function(MongooseModel, options) {
var Collection = MongooseModel;
...
return Collection
};
最佳答案
有一些方法可以尝试并做到这一点,但不确定您尝试扩展的到底是什么。
您可以添加实例方法<schema>.methods.<mymethod> = function(){}
// define a schema
var animalSchema = new Schema({ name: String, type: String });
// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function (cb) {
return this.model('Animal').find({ type: this.type }, cb);
}
而且你可以添加静态方法<schema>.statics.<mymethod> = function(){}
// assign a function to the "statics" object of our animalSchema
animalSchema.statics.findByName = function (name, cb) {
return this.find({ name: new RegExp(name, 'i') }, cb);
}
var Animal = mongoose.model('Animal', animalSchema);
Animal.findByName('fido', function (err, animals) {
console.log(animals);
});
示例来自 mongoose docs - 只需搜索“静态”。
您可以在模型上调用的静态函数。这些方法通常是处理从查询返回的文档实例或使用 new
创建的文档实例的函数。 .
关于javascript - 有没有更优雅的 "fake"类继承方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33313202/