Skip to content

Instantly share code, notes, and snippets.

@aheckmann
Created June 7, 2012 15:25
Show Gist options
  • Save aheckmann/2889412 to your computer and use it in GitHub Desktop.
Save aheckmann/2889412 to your computer and use it in GitHub Desktop.
mongoose update,new,remove events
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();
});
});
});
});
})
});
@sourcepirate
Copy link

@codehatcher what version of mongoose are you using ?

@capaj
Copy link

capaj commented Nov 17, 2015

might be nicer to implement the _wasnew via an external array I think

@kmanaseryan
Copy link

I have the same problem also

@terry-fei
Copy link

it seems does not work now

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