【发布时间】:2017-09-01 06:43:25
【问题描述】:
背景
我正在为国家/地区定义 Mongoose 模式,我在其中存储国家/地区名称及其 ISO alpha2 和 ISO alpha3 代码。
这些 ISO 代码只是国家名称的缩写。例如,西班牙是 ES,美国是美国,等等。
目标
我的目标是进行模式验证,以便在集合中插入国家/地区时代码具有正确数量的字母。
一个 ISO alpha2 代码只能有 2 个字符,而一个 ISO alpha3 代码可以有 3 个字符。
问题
为了实现这一点,我有一个验证函数来检查给定代码的大小是否正确:
const hasValidFormat = (val, size) => val.length === size;
我正在尝试将此函数用作我的验证器:
"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 for alpha-2 type ISO code."
}
},
alpha3: {
type: String,
validate: {
validator: hasValidFormat(val, 3),
message: "Incorrect format for alpha-3 type ISO code."
}
}
}
};
module.exports = new mongoose.Schema(countrySchema);
module.exports.countrySchema = countrySchema;
问题是我有错误val is not defined 并且代码无法运行。这很混乱,因为根据Mongoose docs for custom validators,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: val => hasValidFormat(val, 2),
message: "Incorrect format for alpha-2 type ISO code."
}
},
alpha3: {
type: String,
validate: {
validator: val => hasValidFormat(val, 3),
message: "Incorrect format for alpha-3 type ISO code."
}
}
}
};
module.exports = new mongoose.Schema(countrySchema);
module.exports.countrySchema = countrySchema;
它会起作用的!
问题
谁能解释一下为什么第一个例子不起作用,而第二个例子起作用?
【问题讨论】:
标签: node.js mongodb validation mongoose schema