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
validation ignored if the path set as 'select: false' #13062
Comments
The following script throws an error as expected. Please modify the below script to demonstrate the issue you're seeing. const mongoose = require('mongoose');
const testSchema = new mongoose.Schema({
name: { type: String, required: true },
age: { type: Number, required: true, select: false }
});
const Test = mongoose.model('Test', testSchema);
async function run() {
await mongoose.connect('mongodb://localhost:27017');
await mongoose.connection.dropDatabase();
await Test.create({
name: 'Test Testerson',
age: 0
});
const doc = await Test.findOne();
doc.age = null;
doc.name = 'Test';
await doc.save();
console.log('done');
}
run(); |
"links" set to undefined manually in pre save middleware, but finally there is no error. When you turn on select option, then error occur as expected. Maybe it's a very weird usage situation above but actually the most interesting thing I see are just:
|
const mongoose = require('mongoose');
const testSchema = new mongoose.Schema({
name: { type: String, required: true },
age: { type: Number, required: true, select: false },
links: { type: String, required: true, select: false }
});
testSchema.pre('save', function() {
this.links = undefined;
});
const Test = mongoose.model('Test', testSchema);
async function run() {
await mongoose.connect('mongodb://localhost:27017');
await mongoose.connection.dropDatabase();
await Test.create({
name: 'Test Testerson',
age: 0,
links: 'some init links'
});
const doc = await Test.findOne(); // error occur: .select('+links');
doc.name = 'Test';
await doc.save();
console.log('what is doc', doc);
console.log('done');
}
run(); |
Avoid saving changes to non-modified paths
Prerequisites
Issue
Related Issue:
#730
[https://github.com//issues/730](issue 730)
At most time, before doc.save(), validation will run. But if select option set to false on some path, it does not run validation on that path even there's a required validator until select set to true. This idea may come from #730. That's reasonable enough.
But it's so sad that this rationale cannot be searched on the documentation. I only found it in source code, around line 2610:
I just thought full validation will run rather than select option determines. It wasted some time.
So, for making more lives much easier, I think this rule should be added to the documentation directly and explicitly, at least a warning item of rules on validation ;)
The text was updated successfully, but these errors were encountered: