Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Direct object assignment causes wrong array validation #4145

Closed
dbellavista opened this issue May 11, 2016 · 2 comments
Closed

Direct object assignment causes wrong array validation #4145

dbellavista opened this issue May 11, 2016 · 2 comments
Milestone

Comments

@dbellavista
Copy link

dbellavista commented May 11, 2016

Soo this is a bit tricky. If you have a Schema defining an object with a nested array of schemas and you perform a direct assignent of the nested object, the validator are called twice:

  • Once with this set as the parent object
  • Once with this set as the array schema (desiderata)

This is the minimum code I was able to write to reproduce the issue:

const mongoose = require('mongoose');
// Creating the inner schema with custom validator
const InnerSchema = new mongoose.Schema({
  myfield: {
    type: String,
    validate: {
      validator: myValidator,
      message: 'Message'
    }
  },
  sibling: String
});
// Creating the main schema. The array is nested inside an object
const MySchema = new mongoose.Schema({
  nest: {
    myarray: [InnerSchema]
  },
  rootSibling: String
});

const Model = mongoose.model('MyModel', MySchema);

const inst = new Model({
    rootSibling: 'This is the root sibling'
  });
// Direct object assignment
inst.nest = {
    myarray: [{
      myfield: 'This is my field',
      sibling: 'This is the nested sibling'
    }]
};

inst.save();
// Expected output:
//        This is my field , This is the nested sibling , undefined
// Actual output:
//         This is my field , undefined , This is the root sibling
//         This is my field , This is the nested sibling , undefined


// My validator prints the value, this.sibling and this.rootSibling
function myValidator(v) {
  console.log(v, ',', this.sibling, ',', this.rootSibling);
}
@dbellavista
Copy link
Author

And if I do this:

const inst = new Model({
    rootSibling: 'This is the root sibling',
    nest: {
      myarray: [{
        myfield: 'This is my field',
        sibling: 'This is the nested sibling'
      }]
    }
  });

it works as expected. Also this code works:

const inst = new Model({
    rootSibling: 'This is the root sibling'
  });
inst.nest.myarray = [{
  myfield: 'This is my field',
  sibling: 'This is the nested sibling'
}];

@dbellavista
Copy link
Author

Sorry, forgot: Node v6.1.0, mongoose 4.4.16. I confirm that version 4.4.15 doesn't have this bug.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants