Mongoose: browser-side validation on nested schema skips validating path on parent

Created on 6 Feb 2019  路  3Comments  路  Source: Automattic/mongoose

Do you want to request a feature or report a bug?
bug

What is the current behavior?

If the current behavior is a bug, please provide the steps to reproduce.

Hard to describe this properly, but modifying a nested document doesn't seem to mark as modified the field that's the nested schema on the parent... So validating skips it :'(.

Yeah, that was a mouthful. A test in browser.test.js would illustrate it better ;)

    it('validates parent when child schema modified (gh-7493)', function(done) {
      const childSchema = new Schema({
        from: {
          type: Number,
          min: 0,
          max: 100
        },
        to: {
          type: Number,
          min: 0,
          max: 100
        }
      });
      const parentSchema = new Schema({
        payrate: {
          type: childSchema,
          default: {},
          validate: [
            {
              isAsync: false,
              validator: (payrate) => {
                return !payrate.from || !payrate.to || payrate.from<payrate.to;
              }
            }
          ]
        }
      });

      const parentDoc = new Document({}, parentSchema);

      parentDoc.payrate.from = 20;
      parentDoc.payrate.to = 10;
      console.log('before - fails to validate');
      assert.ok(parentDoc.validateSync());

      parentDoc.markModified('payrate');
      console.log('after - works');
      assert.ok(parentDoc.validateSync());

      done();
    });

The test above fails, but if you comment out the first assert.ok() it passes.

What is the expected behavior?

No need to manually mark modified.

Please mention your node.js, mongoose and MongoDB version.

node 10, and mongo nothing ;) browser-side.

Tested this on master and it still fails.

confirmed-bug

All 3 comments

Looks like this isn't a bug with just the browser side. The issue is because of the default and the fix for #5885: Mongoose skips validators on single nested paths if just a subpath is modified, but we don't account for cases where the single nested path has a default and a subpath is modified. Fix will be in 5.4.12 :+1:

you're a machine! \o/

"I am a cybernetic organism, living tissue over a metal endoskeleton" :rofl:

Terminator

Was this page helpful?
0 / 5 - 0 ratings

Related issues

gustavomanolo picture gustavomanolo  路  3Comments

Soviut picture Soviut  路  3Comments

Igorpollo picture Igorpollo  路  3Comments

CodeurSauvage picture CodeurSauvage  路  3Comments

lukasz-zak picture lukasz-zak  路  3Comments