2015-10-24 90 views
3

由于猫鼬处理它们的方式以及因为mongoose=require('mongoose')是singelton,我还没有找到一种简单的方法来扩展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中注册的模型创建“文档”时出错。

所以,现在我所做的是完全不雅:

“使用严格的”;

var _ = require('lodash'); 

module.exports = function(MongooseModel, options) { 

    var Collection = MongooseModel; 

    ... 

    return Collection 

}; 
+1

我不认为这是不好看的。您只是将它用作Mixin,它是Composition。它看起来很好,因为你的对象和MongooseModel之间的依赖关系较少。 –

+0

如果它困扰你,你可能会考虑创建一个工厂方法并在那里移动这个_.assign逻辑。然后像使用构造函数一样使用此Factory Method。 –

+1

为了说明为什么我认为这看起来很好,埃里克艾略特有关于这个问题的文章和谈话:http://ericleads.com/2013/06/classical-inheritance-is-obsolete-how-to-think- in-prototypal-oo /和https://medium.com/javascript-scene/common-misconceptions-about-inheritance-in-javascript-d5d9bab29b0a#.sq5r9ln5f –

回答

1

有一些方法可以尝试并做到这一点,尽管不确定你试图扩展什么。

您可以添加实例方法<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创建的函数。

相关问题