Model.update Validators: No access to "this", specifically in subschemas
See original GitHub issueUsing this
in my validators works for document validation, but breaks (throws errors) on query validation.
Is there an option I’m not aware of that would help me achieve this?
My root issue is that I want to mutually validate 2 fields against each other, and had been using this
as a way to access each of them.
var schema = new Schema({
smaller: {type: Number, validate: validateRelative},
larger: {type: Number, validate: validateRelative}
}, {_id: false});
function validateRelative(val, done) {
// Works for document validation,
// but throws (this not defined) on query (update) validation
if(this.smaller > this.larger) {
return done(false, "`larger` must be greater than `smaller`");
}
return done;
}
Another alternative I could think of, but couldn’t figure out how to implement would be defining “root” validation on my schema, e.g.:
// Is there a way to do this??
schema.path(/* root */).validate(validateRelative);
function validateRelative(subDoc, done) {
if(subDoc.smaller > subDoc.larger) {
return done(false, "Path `larger` must be greater than path `smaller`");
}
return done;
}
Issue Analytics
- State:
- Created 7 years ago
- Comments:6
Top Results From Across the Web
Mongoose find/update subdocument - Stack Overflow
In my CMS there's a panel where I list all the folders and their permissions. The admin can edit a single permission and...
Read more >Re: JSON Schema, Partial Updates, Subschema Validation
Ideally, I would like clients to be able to submit partial updates and validate against the schema for the resource being updated without...
Read more >Mongoose v6.8.1: Validation
Validators are not run on undefined values. The only exception is the required validator. Validation is asynchronously recursive; when you call Model#save, sub- ......
Read more >Applying Subschemas Conditionally - JSON Schema
Therefore, if the “country” property is not defined, the default behavior is to validate “postal_code” as a USA postal code. The “default” keyword...
Read more >Resolve template validation or template format errors in ... - AWS
For "JSON not well-formed" or "YAML not well-formed" errors, see the Validate template syntax section. For "Unresolved resource dependencies [ ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Fixed, see http://mongoosejs.com/docs/validation.html#update-validators-and-this . Looks like our docs build was broken.
Thanks for pointing that out, fixed.