var mongoose = require('mongoose');
mongoose.connect('localhost', 'testing_emitUpdate');
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 () {
console.error('this was new');
});
schema.post('update', function () {
console.error('this was an update');
});
schema.post('remove', function () {
console.error('this was removed');
});
// 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) {
doc.remove(function () {
mongoose.connection.db.dropDatabase(function () {
mongoose.connection.close();
});
});
});
});
})
});