Skip to content

Instantly share code, notes, and snippets.

@oshybystyi
Last active March 31, 2018 11:08
Show Gist options
  • Save oshybystyi/ad98f3963ab797b0df32 to your computer and use it in GitHub Desktop.
Save oshybystyi/ad98f3963ab797b0df32 to your computer and use it in GitHub Desktop.
Checking how to know old attribute values in mongoose middleware
var mongoose = require('mongoose'),
moment = require('moment');
mongoose.connect('mongodb://127.0.0.1:27017/test', function(err) {
if (err) {
throw err;
}
var TestModel = require('./TestModel');
TestModel.findOne({}, function(err, doc) {
if (!doc) {
var doc = new TestModel();
}
doc.name = 'Test 1 - ' + moment().format('HH:mm:ss:SS');
doc.ready = !doc.ready;
doc.save(function(err) {
if (err) {
throw err;
}
mongoose.connection.close();
});
});
});
{
"name": "test-model-attribute-old-value",
"version": "0.0.1",
"description": "Checking how to know old attribute values in mongoose middleware",
"main": "app.js",
"dependencies": {
"moment": "^2.10.3",
"mongoose": "^4.0.7"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var testModelSchema = new Schema({
name: String,
ready: {type: Boolean, default: false}
});
testModelSchema.pre('init', function(done) {
console.log('------------------');
console.log('Pre init attributes');
if (!this.isNew) {
console.log(this);
} else {
console.log('The doc is new, run app once again');
}
console.log('------------------');
done();
});
testModelSchema.post('init', function(model) {
console.log('------------------');
console.log('Post init attributes');
if (!this.isNew) {
console.log(model);
model.oldValues = JSON.parse(JSON.stringify(model));
console.log('Setting this.oldValues');
} else {
console.log('The doc is new, run app once again');
}
console.log('------------------');
});
testModelSchema.pre('save', function(done) {
console.log('------------------');
console.log('Pre save attributes');
if (!this.isNew) {
console.log(this);
} else {
console.log('The doc is new, run app once again');
}
this.wasNew = this.isNew; // this is just for post('save') to knew
console.log('------------------');
done();
});
testModelSchema.post('save', function(model) {
console.log('------------------');
console.log('Post save attributes');
if (!model.wasNew) {
console.log(model);
console.log('The old attributes (model.oldValues)')
console.log(model.oldValues);
} else {
console.log('The doc is new, run app once again');
}
console.log('------------------');
});
module.exports = mongoose.model('TestModel', testModelSchema);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment