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.

Revisions

  1. zoellner revised this gist Nov 8, 2017. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions index.js
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,7 @@
    'use strict';

    //see https://github.com/Automattic/mongoose/issues/5800

    const mongoose = require('mongoose');
    const assert = require('assert');

  2. zoellner revised this gist Nov 8, 2017. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion index.js
    Original file line number Diff line number Diff line change
    @@ -4,7 +4,7 @@ const mongoose = require('mongoose');
    const assert = require('assert');

    mongoose.Promise = global.Promise;
    mongoose.connect('mongodb://localhost/mongoose-bug-hook-set');
    mongoose.connect('mongodb://localhost/mongoose-gh-5800');

    const MainSchema = new mongoose.Schema({
    a: {
  3. zoellner created this gist Nov 8, 2017.
    52 changes: 52 additions & 0 deletions index.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    'use strict';

    const mongoose = require('mongoose');
    const assert = require('assert');

    mongoose.Promise = global.Promise;
    mongoose.connect('mongodb://localhost/mongoose-bug-hook-set');

    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);
    });
    });
    });
    });
    });