node.js - Mongoose: Simple custom validation function not working -
background
i defining mongoose schema countries, store country name, , iso alpha2 , iso alpha3 codes.
these iso codes, abbreviations country names. example, spain es, united sates us, , on.
objective
my objective schema validation codes have right amount of letters when inserting country in collection.
an iso alpha2 code can have 2 characters, , iso alpha3 code can have 3.
problem
to achieve have validation function checks if given code has correct size:
const hasvalidformat = (val, size) => val.length === size;
and trying use function validator:
"use strict"; const mongoose = require("mongoose"); const hasvalidformat = (val, size) => val.length === size; const countryschema = { name: { type: string, required: true }, isocodes:{ alpha2: { type: string, required:true, validate: { validator: hasvalidformat(val, 2), message: "incorrect format alpha-2 type iso code." } }, alpha3: { type: string, validate: { validator: hasvalidformat(val, 3), message: "incorrect format alpha-3 type iso code." } } } }; module.exports = new mongoose.schema(countryschema); module.exports.countryschema = countryschema;
the problem have error val not defined
, code wont run. confusing, because according mongoose docs custom validators, validator
field function!
however
if change previous code to:
"use strict"; const mongoose = require("mongoose"); const hasvalidformat = (val, size) => val.length === size; const countryschema = { name: { type: string, required: true }, isocodes:{ alpha2: { type: string, required:true, validate: { validator: val => hasvalidformat(val, 2), message: "incorrect format alpha-2 type iso code." } }, alpha3: { type: string, validate: { validator: val => hasvalidformat(val, 3), message: "incorrect format alpha-3 type iso code." } } } }; module.exports = new mongoose.schema(countryschema); module.exports.countryschema = countryschema;
it work!
question
can explain me why first example doesn't work, , second does?
this because validator
function take 1 parameter.
according documentation, if validator
function takes 2 parameters, mongoose assume 2nd argument callback.
"custom validators can asynchronous. if validator function takes 2 arguments, mongoose assume 2nd argument callback."
source: http://mongoosejs.com/docs/validation.html
you first code fails because mongoose seeing async validation, not case. golden rule, validation functions should inline.
you can achieve behavior looking bu using closer function, in second code sample.
thanks,
Comments
Post a Comment