2016-02-18 82 views
0

我想能夠定義類的貓鼬,而不是使用正常的架構,然後爲其定義功能。 我有一個像這樣一類:如何從一個類(函數)創建一個貓鼬模式

var odd = function() { 
    this.name = String; 
    this.someprop = { 
     type: String, 
     required: true 
    } 
} 

這個類,那麼有以下功能:

odd.prototype.cake = function() { 
    return "This cake has the name \"" + this.name + "\"."; 
} 

通常在貓鼬我必須定義的最後一個函數我已經創建了我的架構後,但我失去我通過這樣做的智能感(比現在更多)。

有沒有一種好方法可以讓我的課變成貓鼬模式而沒有太多麻煩?

回答

0

我已經能夠找到的最好的方法是創建一個輔助功能,這樣,這是我然後放入一個單獨的文件:

var mongoose = require("mongoose"); 
var Schema = mongoose.Schema; 
var helpers = require("./helpers"); 

/** 
* Dark wizardry function that creates a mongoose schema from a normal JS class 
* Objects can also be passed along, and any properties that has methods will be turned into methods on the mongoose Schema. 
* @param c The class to creare the schema from 
* @param options The additional options to pass to the schema creation 
* @returns {Schema} A new mongoose schema for the describing the given class 
*/ 
module.exports = function(c, options) { 
    var f = null; 
    // Figure out if f is an object or a function, and take appropriate action 
    if(helpers.isFunction(c)) { 
     f = new c(); 
    } else if(typeof f === "object") { 
     f = c; 
    } else { 
     throw new TypeError("Class schema cannot work with that type. Whatever it was you supplied, probably a simple type. "); 
    } 

    var prop; 
    var o = {}; 
    // Save all the properties of f into a new object 
    for(prop in f) { 
     var p = f[prop]; 
     switch (p) { 
      case String: 
      case Number: 
      case Date: 
      case Buffer: 
      case Boolean: 
      case mongoose.Types.Mixed: 
      case mongoose.Types.ObjectId: 
      case Array: 
       o[prop] = p; 
       break; 
      default: 
       if(!helpers.isFunction(p)) { 
        o[prop] = p; 
       } 
     } 
    } 
    // Create the schema 
    var sch = new Schema(o, options); 
    // Create the methods for the schema 
    for(prop in f) { 
     if (prop in f) { 
      var func = f[prop]; 
      switch (func) { 
       case String: 
       case Number: 
       case Date: 
       case Buffer: 
       case Boolean: 
       case mongoose.Types.Mixed: 
       case mongoose.Types.ObjectId: 
       case Array: 
        continue 
      } 
      if (helpers.isFunction(func)) { 
       sch.methods[prop] = func; 
      } 
     } 
    } 
    return sch; 
}; 

我helpers.js包含isFunction一個很簡單的功能:

function isFunction(f) { 
    return typeof f === "function"; 
} 

exports.isFunction = isFunction; 

然後,每當我想要一個貓鼬的模式我只是做到以下幾點:

var mongoose = require("mongoose"); 
var classSchema = require("./class-schema"); 
var odd = function() { 
    ... 
} 

odd.prototype.cake = function() { 
    ... 
} 

var oddSchema = classSchema(odd, {timestamps: true}); 

module.exports = mongoose.model("Odd", oddSchema); 

這將創建一個具有與原始odd類相同的屬性和相同功能的模型。