Skip to content

Instantly share code, notes, and snippets.

@aheckmann
Created March 27, 2012 12:15
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aheckmann/2215393 to your computer and use it in GitHub Desktop.
Save aheckmann/2215393 to your computer and use it in GitHub Desktop.
mongoose: emit update or create
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('localhost', 'testing_emitUpdate');
var schema = new Schema({
name: String
});
schema.pre('save', function (next) {
this._wasNew = this.isNew;
next();
});
schema.post('save', function () {
if (this._wasNew) console.error('new!');
else console.error('updated!');
});
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) {
mongoose.connection.db.dropDatabase(function () {
mongoose.connection.close();
});
});
});
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment