Description
Do you want to request a feature or report a bug?
Possibly a bug
What is the current behavior?
Document.set causes entire schema array validation.
If the current behavior is a bug, please provide the steps to reproduce.
When using the following schema:
const SectionSchema = new Schema({
title: {
type: String,
required: true,
maxlength: 24
},
state: {
type: String,
validate: function(v) {
console.log(`@section '${this.title}' state is validating`)
return true;
}
}
}, {_id: false});
const RootSchema = new Schema({
name: {
type: String,
required: true
},
sections: [SectionSchema]
});
Updating a SectionSchema
state
by a dot notation path through the set and save triggers all RootSchema
sections array items validate
methods:
// Entries in the Root schema:
// { name: "Test1, sections: [{ title: "foo", state: ""}, { title: "bar", state: ""}, , { title: "boo", state: ""}] }
const doc = Root.findOne({name: "Test1"})
// Update first section state
doc.set("sections.0.state", "hello world", String);
// Commit modified-only changes
await doc.save({validateModifiedOnly: true});
// Console output (should've validate only updated field in this case)
// @section 'foo' state is validating
// @section 'bar' state is validating
// @section 'boo' state is validating
This is interesting, because updateOne
behavior is slightly different and it just works fine while updating the same path:
const doc = Root.findOne({name: "Test1"})
// Update directly
await doc.updateOne({
$set: { "sections.0.state": "john doe" }
}, { runValidators: true });
// Console output:
// @section 'foo' state is validating
I cannot make use of the updateOne
because I need to utilize the save
middleware.
What is the expected behavior?
When using Document.prototype.set
to explicitly update a value, I believe that mongoose shouldn't wastefully validate unmodified array items.
What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.
- mongodb: 3.6.4
- mongoose: 5.11.8
- nodejs: 14.10.0