Created
September 6, 2012 19:35
-
-
Save bsimpson/3659771 to your computer and use it in GitHub Desktop.
Extending Mongoose.js Schemas with functions declared elsewhere
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
// models/player.js | |
var Player = { | |
statics: { | |
foo: function() { | |
console.log('foo'); | |
} | |
}, | |
methods: { | |
bar: function() { | |
console.log('bar'); | |
} | |
} | |
}; | |
exports.statics = Player.statics; | |
exports.methods = Player.methods; | |
// database/schema.js | |
var mongoose = require('mongoose'), | |
Schema = mongoose.Schema, | |
playerModelMethods = require('../models/player'), | |
_ = require('underscore'); | |
var PlayerModel = new Schema({ | |
name: String | |
}); | |
_.extend(PlayerModel, playerModelMethods); | |
connect = function(db, cb) { | |
mongoose.connect(db); | |
var Player = mongoose.model('players', PlayerModel); | |
return cb({ | |
Player: Player | |
}); | |
}; | |
module.exports = { connect: connect }; | |
// In a Node REPL | |
> db = require('./database/schema'); | |
> models = db.connect('mongodb://localhost/db', function(a) { return a }); | |
> models.Player | |
{ [Function: model] modelName: 'players', foo: [Function] } | |
> models.Player.foo() | |
foo | |
> player = new models.Player(); | |
{ _id: 5048faa8abb6407343000002 } | |
> player.bar() | |
bar |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment