Skip to content

Instantly share code, notes, and snippets.

@zoellner
Last active November 8, 2017 19:01
Show Gist options
  • Save zoellner/f022ac62a7ed968a85784edf1a6690c8 to your computer and use it in GitHub Desktop.
Save zoellner/f022ac62a7ed968a85784edf1a6690c8 to your computer and use it in GitHub Desktop.
mongoose-bug-set-pre-save-hook-with-select
'use strict';
//see https://github.com/Automattic/mongoose/issues/5800
const mongoose = require('mongoose');
const assert = require('assert');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/mongoose-gh-5800');
const MainSchema = new mongoose.Schema({
a: {
b: {type: String, default: 'some default'},
c: {type: Number, default: 0},
d: {type: String}
},
e: {type: String}
});
MainSchema
.pre('save', function(next) {
if (this.isModified()) {
//the expectation would be that only a.c is updated on save, not all of a
this.set('a.c', 100, Number);
}
next();
});
const Main = mongoose.model('Main', MainSchema);
Main.remove({}, (err) => { //reset
assert.ifError(err);
Main.create({a: {b: 'not the default', d: 'some value'}, e: 'e'}, (err, m1) => { //create new document
assert.ifError(err);
console.log('m1', m1);
assert.equal(m1.a.b, 'not the default');
assert.equal(m1.a.d, 'some value');
Main.findOne({}).select('e').exec((err, m1select) => { //load with subset of fields
assert.ifError(err);
m1select.e = 'e modified';
m1select.save((err) => {
assert.ifError(err);
Main.findOne({}).exec((err, m1after) => { //load document again
assert.ifError(err);
console.log('m1after', m1after); //at this point a.d is missing and a.b is the default value
assert.equal(m1after.a.b, 'not the default');
assert.equal(m1after.a.d, 'some value');
process.exit(0);
});
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment