Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Alternative Extending Mongoose.js Schemas with functions declared elsewhere
// models/player.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var Player= new Schema({
name: String
});
Player.statics = {
foo: function() {
console.log('foo');
}
}
Player.methods = {
bar: function() {
console.log('bar');
}
}
module.exports = mongoose.model('players', Player);
// database/schema.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
connect = function(db, cb) {
mongoose.connect(db);
var Player = require('../models/player');
return cb({
Player: Player
});
};
module.exports = { connect: connect };
// In 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
You can’t perform that action at this time.