Skip to content

Instantly share code, notes, and snippets.

@wereHamster
Created March 14, 2011 19:16
Show Gist options
  • Save wereHamster/869686 to your computer and use it in GitHub Desktop.
Save wereHamster/869686 to your computer and use it in GitHub Desktop.
mongoose behavior of pre/post-init middleware
var mongoose = require('../lib/mongoose')
mongoose.connect('mongodb://localhost/test');
var Document = null, DocumentSchema = new mongoose.Schema({
data: { type: String },
});
DocumentSchema.pre('init', function(next) {
console.log('pre-init: ' + JSON.stringify(this));
next();
});
DocumentSchema.post('init', function() {
console.log('post-init: ' + JSON.stringify(this));
});
DocumentSchema.method({
fubar: function(hint) {
console.log(hint + ': ' + JSON.stringify(this));
},
});
mongoose.model('Document', DocumentSchema);
Document = mongoose.model('Document');
var doc = new Document({ data: 'this is a document' });
doc.fubar('fresh document');
doc.save(function(err) {
Document.findById(doc._id, function(err, doc) {
doc.fubar('from database');
});
})
@DesignByOnyx
Copy link

Just leaving a note that the pre and post init hooks are not getting fired... at least not when creating a new document in the current version (3.8.8).

@fiddleatwork
Copy link

Same for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment