Created
April 8, 2014 22:57
-
-
Save bouzuya/10205660 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example: | |
// var catModel = require('./cat'); | |
// var Cat = catModel(); | |
// var cat = new Cat({ name: 'mike' }); | |
// cat.say(); //=> myao! i'm mike! | |
// | |
// var mongoose = require('mongoose'); | |
// catModel({ mongoose: new mongoose.Mongoose() }); | |
var defineModel = function(mongoose, modelName, defineSchema) { | |
var modelArgs = [modelName]; | |
if (mongoose.modelNames().indexOf(modelName) < 0) { | |
modelArgs.push(defineSchema(mongoose)); | |
} | |
return mongoose.model.apply(mongoose, modelArgs); | |
}; | |
var defineSchema = function(mongoose) { | |
var Schema = new mongoose.Schema({ | |
name: String | |
}); | |
Schema.methods.say = function() { | |
return 'myao! i\'m ' + this.name + '!'; | |
}; | |
return Schema; | |
}; | |
module.exports = function(options) { | |
var mongoose = options.mongoose ? options.mongoose : require('mongoose'); | |
if (options.mongoose) delete options.mongoose; | |
return defineModel(mongoose, 'Cat', defineSchema); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment