Skip to content

Instantly share code, notes, and snippets.

@nicholasf
Last active September 5, 2015 05:25
Show Gist options
  • Save nicholasf/4ab52e89927ac56699e2 to your computer and use it in GitHub Desktop.
Save nicholasf/4ab52e89927ac56699e2 to your computer and use it in GitHub Desktop.
//running the below produces
// ~/tmp/mongoose-events-test ⮀ ⮀ ⮀ node test ⮂ ruby-2.2.1
// this was new:
// saved: { __v: 0, name: 'emitUpdate', _id: 55ea6f4b05de60396e95e961 }
// saved: { _id: 55ea6f4b05de60396e95e961, name: 'aasdf', __v: 0 }
// saved
// this was removed: { __v: 0, name: 'emitUpdate', _id: 55ea6f4b05de60396e95e961 }
var mongoose = require('mongoose');
mongoose.connect('localhost', 'events');
var Schema = mongoose.Schema;
var schema = new Schema({
name: String
});
// plumbing
schema.pre('save', function (next) {
this._wasnew = this.isNew;
next();
});
schema.post('save', function () {
if (this._wasnew) this.emit('new')
else this.emit('update');
});
// listeners
schema.post('new', function (data) {
console.log('this was new: ') ;
});
schema.post('update', function (data) {
console.log('this was an update: ');
});
schema.post('save', function(data) {
console.log('saved: ', this)
})
schema.post('remove', function (data) {
console.log('this was removed: ', this);
mongoose.connection.close();
});
// test
var A = mongoose.model('A', schema);
mongoose.connection.on('open', function () {
var a = new A({ name: 'emitUpdate' });
a.save(function (err, a) {
if (err) return console.error(err.stack||err);
A.findById(a, function (err, doc) {
if (err) console.error(err.stack||err);
doc.name = 'aasdf';
doc.save(function (err) {
console.log("saved")
a.remove(function(){
// mongoose.connection.close();
})
});
});
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment