-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
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
merge validators from schemaType.prototype.validate definition and schemaType.set #14070
Comments
Does the following? It outputs the same result. import db from "mongoose";
await db.connect("mongodb://127.0.0.1/test");
const defaultValidators = [
{
validator(val, rest) {
const {options} = this.constructor.schema.path(rest.path);
if (options.min) {
if (val.length < options.min) throw `El campo ${rest.path} debe tener al menos ${options.min} elementos`;
}
return true;
},
propsParameter: true
},
{
validator(val, rest) {
const {options} = this.constructor.schema.path(rest.path);
if (options.max) {
if (val.length > options.max) throw `El campo ${rest.path} debe tener a lo más ${options.max} elementos`;
}
return true;
},
propsParameter: true
}
];
db.plugin(schema => {
schema.eachPath((path, schemaType) => {
defaultValidators.forEach(v => schemaType.validate(v));
});
});
const Schema = new db.Schema({
a: {
type: [String],
min: 2,
max: 3,
validate: {
validator(v) {
return v.includes("test3");
},
message: "el campo {PATH} no incluye 'test3'"
}
}
});
const model = db.model("model", Schema);
//console.log("validators", Schema.path("a").validators);
let doc;
const a = [];
for (let i = 1; i <= 5; i++) {
a.push("test" + i);
doc = new model({a});
console.log(doc);
const error = doc.validateSync();
console.log(error?.errors?.a?.reason ?? error?.errors?.a?.message ?? "Sin errores");
}
db.disconnect(); Output:
|
Hi, I know the Maybe I'm too used to "vue mixin way" to define defaults. Regards. |
feat(schematype): merge rather than overwrite default schematype validators
This issue is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 5 days |
Prerequisites
🚀 Feature Proposal
Hi, As
validate
attribute in a schemaType could beFunction|Array|Object
, and you can set it viaschemaType.set
I'll be nice to merge both definitions.Motivation
I want to add a validation set for the schemaType Array (I need this for several types with different validations), to check min and max elements. but if I add other validator in the schemaType definition, it get overwritten.
For now my only choice is to create a plugin who searches in all paths and check if there is a min or max option in an "Array" instance and add a pre or post validate hook to the schema or merge the default validators with the ones declared in Schema, either way Schema.prototype.validate ain't accepts arrays
Example
The text was updated successfully, but these errors were encountered: