Created
June 7, 2012 15:25
-
-
Save aheckmann/2889412 to your computer and use it in GitHub Desktop.
mongoose update,new,remove events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); | |
}); | |
}); | |
}); | |
}) | |
}); |
@STRML, This worked for me just now.
@codehatcher what version of mongoose are you using ?
might be nicer to implement the _wasnew
via an external array I think
I have the same problem also
it seems does not work now
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This doesn't seem to work - hooks.js is looking for the 'new' function, which doesn't exist on documents. I get the following stacktrace:
Which leads to the line: