-
-
Save enesser/ca9ac20a912f6a36ecb1 to your computer and use it in GitHub Desktop.
mongoose: emit update or create
This file contains hidden or 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'); | |
| 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