Skip to content

Direct object assignment causes wrong array validation #4145

@dbellavista

Description

@dbellavista

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions