【问题标题】:Is there a more elegant way to "fake" class inheritance?有没有更优雅的方式来“伪造”类继承?
【发布时间】:2016-01-23 15:08:58
【问题描述】:

由于 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

};

有人有更优雅的解决方案吗?

编辑:

原来上述解决方案不起作用。例如,当 Mongo 尝试从尚未向 Mongoose 注册的模型创建“文档”时,使用 Collection.find({}, function(err, docs) {...}) 会出错。

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

'使用严格';

var _ = require('lodash');

module.exports = function(MongooseModel, options) {

    var Collection = MongooseModel;

    ...

    return Collection

};

【问题讨论】:

  • 我不认为这是不雅的。您只是将其用作 Mixin,即 Composition。对我来说看起来不错,因为您的对象和 MongooseModel 之间的依赖关系较少。
  • 如果它困扰你,你可以考虑创建一个工厂方法并将这个 _.assign 逻辑移到那里。然后像使用构造函数一样使用这个工厂方法。
  • 只是为了阐明为什么我认为这看起来不错,Eric Elliot 有文章并讨论了这个主题:ericleads.com/2013/06/…medium.com/javascript-scene/…
  • 也许我在这里遗漏了一些东西,但不是_.assign,你不能这样做吗:Collection = Object.create(MogooseModel);
  • 在 ES6 中你可以这样做:let Collection = Object.assign(Object.create(MongooseModel), { ... });

标签: javascript mongoose prototype ecmascript-6 lodash


【解决方案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 - 只需搜索“statics”即可。

您可以在模型上调用的静态函数。这些方法通常是处理从查询返回或使用new 创建的文档实例的函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-04
    • 2022-11-13
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多