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();
});
});
});
});
})
});
@STRML
Copy link

STRML commented Jun 28, 2012

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:

 TypeError: Cannot read property 'numAsyncPres' of undefined
  at model.module.exports._lazySetupHooks (proj/node_modules/mongoose/node_modules/hooks/hooks.js:162:49)
  at model.module.exports.post (proj/node_modules/mongoose/node_modules/hooks/hooks.js:143:10)
  at model.Document.doQueue (proj/node_modules/mongoose/lib/document.js:1129:41)
  at model.Document (proj/node_modules/mongoose/lib/document.js:55:8)
  at model.Model (proj/node_modules/mongoose/lib/model.js:26:12)
  at new model (proj/node_modules/mongoose/lib/model.js:896:11)
  ...

Which leads to the line:

_lazySetupHooks: function (proto, methodName, errorCb) {
  if ('undefined' === typeof proto[methodName].numAsyncPres) {
      this.hook(methodName, proto[methodName], errorCb);
  }
}

@avishaan
Copy link

@STRML, This worked for me just now.

@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